我希望将子div延伸到与父母的父级相同的宽度。所以使用HTML结构:
<div class="pp">
<div class="p">
<p>
Some text
</p>
<div class="c">
This is the thingy!
</div>
<p>
Some more text
</p>
</div>
</div>
我希望div.c
扩展到div.pp
的边界。
我知道这可能带有负边距,但在我的情况下,我事先并不知道div.pp
的边距。我知道我可以写一些JavaScript来做这件事,但我对只有CSS的解决方案很感兴趣。我也知道改变HTML的结构可以解决这个问题,但这也不是一个选择。
这是一个小提琴,说明HTML和一些有用的CSS:
https://jsfiddle.net/y37mLkzu/1/
有一个例子可以用负边距来解决这个问题。
答案 0 :(得分:2)
我不确定这是否适用于您的情况,但这是唯一不使用固定减去边距且仅使用纯CSS的方法。我已将:before
和:after
添加到.c
,并将它们绝对定位在.c
元素的任意一侧。我还在.pp
包装器中添加了隐藏溢出,以切断多余的绝对定位元素。
p {
margin:0;
}
.pp {
padding: 0 6px 0 6px;
width: 100px;
background-color: black;
overflow: hidden;
}
.p {
background-color:white;
}
.c {
background-color:red;
position: relative;
}
.c:before, .c:after {
content:"";
position: absolute;
top:0;
background: red;
height:100%;
width:100%;
}
.c:before {
left:-100%;
}
.c:after {
right:-100%;
}
<div class="pp">
<div class="p">
<p>
Some text
</p>
<div class="c">
This is the thingy!
</div>
<p>
Some more text
</p>
</div>
</div>
答案 1 :(得分:-1)
你不能使用职位吗?只是好奇才知道。如果我使用position:absolute
,它将有效。