如何将鼠标元素悬停在父元素上,但背景颜色是否延伸?

时间:2018-02-16 18:57:33

标签: html css background-color

我有一个包含多个子元素的父元素。父元素上有填充以缩进所有子元素。是否可以将鼠标悬停在子元素上并使背景颜色一直变为父元素的边框?

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;
}

背景颜色仅延伸到子元素的末尾。是否有可能将其伸展到父母的边界?

2 个答案:

答案 0 :(得分:2)

您只需将填充移动到子元素:

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

如果你不想改变填充,你可以考虑伸展的伪元素占据整个宽度:

&#13;
&#13;
.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;
}
&#13;
<div class="parent">
  <div class="child">Child 1</div>
  <div class="child">Child Number 2</div>
  <div class="child">Child Numero 3</div>
</div>
&#13;
&#13;
&#13;

答案 1 :(得分:0)

为孩子做宽度100%。

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