A block-level element always starts on a new line and takes up the full width available
If that parent container has padding, the child can still only take up the available space that is left within the content area.
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>
If you know the amount of padding the parent container has, you can apply negative left & right margins (of the same amount) to the children. This is commonly seen in CSS framework grid systems.
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>
If you don't know the parent padding but only have a single child, you can use position: absolute; left: 0; right: 0
as long as the parent is positioned.
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>
Now when you want the child to be full screen, you can now toggle between absolute
and fixed
to get it from one state to the other.
$(".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>