This image describes the story. I want to make purple div same as green div . 有人可以解释我如何在未知父级边距和填充的情况下使子级div全宽吗?
<div class="parent">
<div class="child1">
</div>
<div class="child2">
</div>
</div>
我主要坚持调整子div的边距和填充。
注意:父div的宽度为边距,填充为未知 plz checkout the image red portion is parent and purple color is child, I want the purpule portion come out and take the full width of viewport
答案 0 :(得分:0)
您可以在CSS中使用width: 100%;
。
.child1 {
width: 100%;
}
<div class="child1"></div>
答案 1 :(得分:0)
block-level element总是从新行开始并占据可用的全部宽度
如果该父容器具有填充,则子容器仍只能占用内容区域内剩余的可用空间。
body {
margin: 0;
}
.parent {
padding: 10px;
margin: 20px;
background: #FB061B;
}
.child {
background: #7C73A5;
}
<div class="parent">
<div class="child">
child1
</div>
<div class="child">
child2
</div>
</div>
如果知道父容器的填充量,则可以对子容器应用负的左右边距(相同量)。这在CSS框架网格系统中很常见。
body {
margin: 0;
}
.parent {
padding: 10px;
margin: 20px;
background: #FB061B;
}
.child {
background: #7C73A5;
margin-left: -10px;
margin-right: -10px;
}
<div class="parent">
<div class="child">
child1
</div>
<div class="child">
child2
</div>
</div>
如果您不知道父填充,但只有一个孩子,则只要放置父就可以使用position: absolute; left: 0; right: 0
。
body {
margin: 0;
}
.parent {
padding: 10px;
margin: 20px;
background: #FB061B;
position: relative;
}
.child {
background: #7C73A5;
position: absolute;
left: 0;
right: 0;
}
<div class="parent">
<div class="child">
child1
</div>
</div>
现在,当您希望孩子全屏显示时,现在可以在absolute
和fixed
之间切换,以使其从一种状态进入另一种状态。
$(".children").click(function() {
$(this).toggleClass("is-fixed")
});
body {
margin: 0;
}
.parent {
padding: 10px;
margin: 20px;
background: #FB061B;
position: relative;
height: 100px;
}
.children {
background: #7C73A5;
position: absolute;
left: 0;
right: 0;
top: 0;
}
.is-fixed {
top: initial;
background: green;
position: fixed;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="parent">
<div class="children">
click to toggle between absolute/fixed
<div>child1</div>
<div>child2</div>
<div>child3</div>
</div>
</div>