FORSMILE
JA
CSS2020/12/21

Making a Child Element Full Screen Width Beyond Its Parent's Boundaries Using CSS

While not often requested for smartphone designs, PC designs sometimes have a specific need for a section to have a full-width background. If the design isn't responsive, simply using negative margins to expand the element would work. However, non-responsive designs are quite rare now...

Back to Blog

While not often requested for smartphone designs, PC designs sometimes have a specific need for a section to have a full-width background. If the design isn't responsive, simply using negative margins to expand the element would be fine. However, it's rare to see a non-responsive design these days.

CSS TO MAKE A CHILD ELEMENT FULL SCREEN WIDTH BEYOND ITS PARENT'S BOUNDARIES

Sample

CODE

css
// 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

While it does make the child element span the full screen width, there are a few caveats. If it cannot be applied, it's probably faster to simply move the element out of the parent.

Center Point is Parent Element's Center

This means if the parent element is not centered on the screen, the child element will also be misaligned.

Scrollbar Calculation

On long pages, a scrollbar will appear on the right side of the browser. If you don't account for this in your calculations, a horizontal scrollbar will appear at the bottom.

You can also avoid the horizontal scrollbar by setting `overflow: hidden;` on the outermost element.

USING POSITION

This can also be achieved using `position`. The same caveats mentioned above still apply, but it's best to choose the method that is easier to adjust during coding.

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

RECOMMENDED CSS/SASS BOOKS

For CSS and SCSS, once you understand the basics, it's often quicker to look things up with Google. As long as you grasp how CSS works and how to use SASS, you'll be fine with the fundamentals.

HTML & CSS and Web Design Introductory Course: Master Everything in One Book

📦
Amazon で関連書籍・ツールを検索
CSS frontend design book
Amazonで探す →(アソシエイトリンク)