[英]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: 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: 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?
是否可以将其延伸到父母边界?
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>
Do width 100% for child.为孩子做宽度 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>
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.