how can I make the child take the full width of the page
something
-
You can position the child relative and left: 50%
and then translate it by -50% in the x-axis to re-align it with the edge of the screen. This works because left: 50%
is half of the parent width while the transform: translateX(-50%)
is half of the element itself. This relies on the original container being centered so may not work for all cases.
.container {
background: gray;
width: 80%;
margin: auto;
}
.child {
position: relative;
left: 50%;
transform: translateX(-50%);
width: 100vw;
background: red;
}
<div class='container'>
<div>Centered</div>
<div class='child'>Something</div>
<div>Centered</div>
<div>Centered</div>
<div>Centered</div>
</div>
讨论(0)
-
Consider negative margin.
.container {
width: 90%;
margin: 0 auto;
padding: 10px 0;
background: red;
}
.child {
height: 50px;
background: blue;
margin: 0 calc(-5% / 0.9);
/*
The container is taking 90% of 100% so we are missing 10%
we plit this value on both sides (5% + 5%) and since percentage is relative
to parent so to make the percentage inside .child relative to body
we divide by the percentage of container
it should be then 5%/0.9 or 5%*1.11
*/
}
body {
margin: 0;
}
<div class='container'>
<div class='child'>
something
</div>
</div>
With CSS variable you can have something more dynamic:
.container {
width: calc(var(--s)*100%);
margin: 5px auto;
padding: 10px 0;
background: red;
}
.child {
height: 50px;
background: blue;
margin: 0 calc((-50% * (1 - var(--s))) / var(--s));
}
body {
margin: 0;
}
<div class='container' style="--s:0.8">
<div class='child'>
something
</div>
</div>
<div class='container' style="--s:0.5">
<div class='child'>
something
</div>
</div>
<div class='container' style="--s:0.2">
<div class='child'>
something
</div>
</div>
In case the container is not centered simply put all the missing margin on one side:
.container {
width: calc(var(--s)*100%);
margin: 5px 0;
padding: 10px 0;
background: red;
}
.child {
height: 50px;
background: blue;
margin-right:calc((-100% * (1 - var(--s))) / var(--s));
}
body {
margin: 0;
}
<div class='container' style="--s:0.8">
<div class='child'>
something
</div>
</div>
<div class='container' style="--s:0.5">
<div class='child'>
something
</div>
</div>
<div class='container' style="--s:0.2">
<div class='child'>
something
</div>
</div>
PS: the use of vw
isn't a good idea because it includes the width of the scroll. So you will have overflow.
.box {
height:50px;
background:red;
width:100vw;
border:5px solid green;
box-sizing:border-box;
}
body {
margin:0;
min-height:200vh;
}
<div class="box"></div>
讨论(0)
-
.child {
width: 100%;
position: absolute;
}
讨论(0)