Fill the screen width of child elements beyond the width of the parent element in CSS

Smartphone design is not required much, but only pc design sometimes there is a request that "I want you to draw the background to the full width only here". If you are not responsive, you can just use a negative margin to expand it. However, it is rare that it is not responsive now.

CSS to fill the window width beyond the width of the parent element

Use vw and calc.
Briefly explain the above.

calc
Allows you to use formulas for layout and singing
vw
You can specify the percentage from the window size

Sample

CODE

// html
<div style="background-color: rgba(255,255,0,1);width: 200px;margin: 20px auto">
    PARENT DIV
    <div class="over-width" style="background-color: rgba(255,0,255,.5)">
        CHILD DIV
    </div>
    PARENT DIV
</div>

// CSS
.over-width {
    margin-left: calc(50% - 50vw);
    margin-right: calc(50% - 50vw);
}

 
 

Usage notes

Certainly, there are child elements full of screen width, but there are some caveats. If it is not applicable, I think that it is faster to put it out to the element from the parent element obediently.

The center point is the center of the parent element

In other words, if the parent element is not in the center of the screen width, the child element will also be shifted.

Calculating scrollbars

If it is a long page vertically, a scroll bar will appear to the right of the browser. If you do not calculate that amount, a horizontal scroll bar will appear at the bottom.
You can also avoid side scrollbars by overflowing: hidden on the outermost element.

When position is used

It can also be achieved using position. There are still caveats like the above, but I think that it is good to choose the one that is easy to adjust for coding.

// position version
.over-width-position {
    width: 100vw;
    position: relative;
    left: 50%;
    transform: translateX(-50%);
}

 
 


Leave a Reply 0

Your email address will not be published.

three + three =