![](/img/trans.png)
[英]On hover of child, change background color of parent container (CSS only)
[英]CSS background color for child container extending till parent container
需要子容器的背景色延伸到視點寬度。 所需的屬性應僅應用於子容器。
我嘗試給子容器大邊框直到父容器,但在高分辨率屏幕上不起作用。
背景色應僅應用於文本區域。
.outer{ height: auto; border: 1px solid red; width: 420px; } .inner{ margin-left: 100px; margin-right: 100px; width: 200px; height: 300px; border: 1px solid green; }
<div class="outer"> <div class="inner">Need background color for child container extending till width of view point. properties needed have to be given only within child container. </div> </div>
這是jsfiddle鏈接,可以更好地理解這種情況:
您可以設置一個包裝器以包含所需的顏色,如下所示:
.bg-wrapper{ background: #54BCDF; /*change to desired color*/ } .outer { height: auto; border: 1px solid red; width: 420px; margin: 0 auto; } .inner { margin-left: 100px; margin-right: 100px; width: 200px; height: 300px; border: 1px solid green; }
<div class="bg-wrapper"> <div class="outer"> <div class="inner">Need background color for child container extending till width of view point. properties needed have to be given only within child container.</div> </div> </div>
請記住,您只能更改子容器的css,可以嘗試對Rick的答案進行此修改以擴展background
:
.outer{ height: auto; border: 1px solid red; width: 420px; } .inner{ margin-left: 100px; margin-right: 100px; width: 200px; height: 300px; border: 1px solid green; } .inner:before { content: ''; background: #54BCDF; /*change to desired color*/ position: absolute; width: 100%; height: 300px; left: 0; z-index: -1; }
<div class="outer"> <div class="inner"> Need background color for child container extending till width of view point. properties needed have to be given only within child container. </div> </div>
但是以.outer
為中心,恐怕您必須添加樣式margin: 0 auto
不能完全確定我是否了解您要執行的操作,但是我試了一下。
在CSS中,如果將邊距更改為padding,則子元素上的任何背景色都將擴展到父元素。 背景顏色包括填充,但不包括邊距。
我還必須將孩子的寬度增加20像素,以使其正確填充。
更新的小提琴: https : //jsfiddle.net/5qp1a3um/1/
.inner{
padding-left: 100px;
padding-right: 100px;
background-color: blue;
width: 220px;
height: 300px;
border: 1px solid green;
}
將父母的位置設置為相對:
.outer {
position: relative;
}
然后在子級上創建一個偽元素,該元素覆蓋父級的范圍(寬度和高度100%)。
給它一個負的z-index,這樣它的背景就不會隱藏內容:
.inner:before {
content: '';
background: lightgreen;
position: absolute;
width: 100%;
height: 100%;
left: 0;
z-index: -1;
}
將孩子的位置設置為相對:
.inner { position: relative; }
現在,偽元素的寬度應為100%加上孩子和父母的寬度之差。
您需要將偽元素向左移動以說明孩子的左邊緣:
.inner:before { content: ''; background: lightgreen; position: absolute; height: 100%; width: calc(100% + 220px); /* parent's width - child's width = 220 */ left: -100px; /* account for left margin */ z-index: -1; }
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.