如何使子元素悬停时背景颜色延伸至父元素?

3

我有一个父元素和多个子元素。父元素有填充以缩进所有子元素。是否可能在悬停在子元素上时,使背景色更改到父元素边框的位置?

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

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

1
你能否发布一下当前的HTML和CSS代码?也许有解决方案,但是如果没有看到任何代码,很难确定哪种方法适合你。 - Huangism
1
我有一个父元素和多个子元素。父元素具有... 请提供代码示例,而不是尝试用文字描述它。 - takendarkk
2个回答

2
您可以将填充移动到子元素中:

.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>

如果您不想更改填充值,可以考虑使用伪元素来拉伸它以占据整个宽度:

.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>


0

子元素宽度设为100%。

.parent {
  border: 1px solid black;
  width: 30%;
  padding: 0.8em 0;
}
.child {
width: 100%;  
}
.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>


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接