Search code examples
htmlcssbackground-color

How to hover on child element but have background-color stretch to the parent?


I have a parent element with multiple child elements. The parent element has padding on it to indent all of the child elements. Is it possible to hover over the child element and have the background color change all the way to the border of the parent element?

HTML:

<div class="parent">
   <div class="child">Child 1</div>
   <div class="child">Child Number 2</div>
   <div class="child">Child Numero 3</div>
</div>

CSS:

.parent {
  border: 1px solid black;
  width: 30%;
  padding: 0.8em 11px 0.8em 13px;
}

.child:hover {
  background-color: blue;
}

The background-color only stretches to the end of the child element. Is it possible to stretch it to the parents border?


Solution

  • You can simply move the padding to child elements:

    .parent {
      border: 1px solid black;
      width: 30%;
      padding: 0.8em 0;
    }
    .child {
      padding:0 11px 0 13px;
    }
    .child:hover {
      background-color: blue;
    }
    <div class="parent">
      <div class="child">Child 1</div>
      <div class="child">Child Number 2</div>
      <div class="child">Child Numero 3</div>
    </div>

    And if you don't want to change the padding you can consider pseudo element that you stretch to take the whole width:

    .parent {
      border: 1px solid black;
      width: 30%;
      padding: 0.8em 11px 0.8em 13px;
      overflow:hidden;
    }
    .child {
      position:relative;
    }
    .child:hover::before {
      content:"";
      position:absolute;
      top:0;
      bottom:0;
      left:-100px;
      right:-100px;
      z-index:-1;
      background-color: blue;
    }
    <div class="parent">
      <div class="child">Child 1</div>
      <div class="child">Child Number 2</div>
      <div class="child">Child Numero 3</div>
    </div>