Avoid container padding when child is hovered

Issue

I created a container div with some children div.
The container has horizontal padding. I need that the children divs change color on hover and I did it, but obviously the container padding did not change color.

To avoid this I can set the padding not to the container but to the children but suppose the container is more complicated, in that case I have to set the padding to all the children and it’s not what I want. Is there a smarter solution?

Expected result on hover:

enter image description here

Here my code so far:

.container {
  background: MidnightBlue;
  padding-left: 20px;
  padding-right: 20px;
}

.row {
  cursor: pointer;
  color: white;
  padding-top: 10px;
  padding-bottom: 10px;
}

.row:hover {
  color: MidnightBlue;
  background: MediumTurquoise;
}
<div class="container">
  <div class="row">item 1</div>
  <div class="row">item 2</div>
  <div class="row">item 3</div>
  <div class="row">item 4</div>
  <div class="row">item 5</div>
</div>

Solution

You could solve the issue you are having by setting negative margin and positive padding on .row when it’s hovered, like below.

margin-inline is a shortcut for margin-left and margin-right.

.container {
  background: MidnightBlue;
  padding-left: 20px;
  padding-right: 20px;
}

.row {
  cursor: pointer;
  color: white;
  padding-top: 10px;
  padding-bottom: 10px;
}

.row:hover {
  color: MidnightBlue;
  background: MediumTurquoise;
  padding-inline: 20px;
  margin-inline: -20px;
}
<div class="container">
  <div class="row">item 1</div>
  <div class="row">item 2</div>
  <div class="row">item 3</div>
  <div class="row">item 4</div>
  <div class="row">item 5</div>
</div>

Answered By – yousoumar

This Answer collected from stackoverflow, is licensed under cc by-sa 2.5 , cc by-sa 3.0 and cc by-sa 4.0

Leave a Reply

(*) Required, Your email will not be published