cheich cheich - 2 months ago 16
CSS Question

Child element 100% width of it's parent with overflow: scroll

I'm searching for a solution to get the child element 100% width of it's parent.

The problem: The parent has

overflow-x: scroll
. Text will insert a scrollbar. Now I want a child to get (the new) width of it's container.

Requirements: Pure CSS solution; no further HTML markup; no fixed width.

width: 100%
will set it only to the init state width of the container.

Here is a fiddle: https://jsfiddle.net/y166e3nb/

Answer

I wasn't sure if you wanted the child to be the width without scrolling or with scrolling, so I came up with both:

Without Scrolling:

<div class="parent">
    I'm a wide parent. My text-content will wrap my box.
    My child should get my new size as 100% width.
    <div class="child">
        I would go over the full width if I could.
    </div>
</div>
.parent {
    background: skyblue;
    width: 350px;
    overflow-x: scroll;
    white-space: nowrap;
    padding: 40px 20px;
}
.child {
    background: springgreen;
    width: calc(100% + 40px);
    padding: 0 0 0 20px;
    margin: 0 0 0 -20px;
}

https://jsfiddle.net/y166e3nb/2/

With Scrolling:

<div class="parent">
    I'm a wide parent. My text-content will wrap my box.
    My child should get my new size as 100% width.
    <div class="child">
        I would go over the full width if I could.
    </div>
</div>
.parent {
    background: skyblue;
    width: 350px;
    overflow-x: scroll;
    white-space: nowrap;
    padding: 40px 20px;
}
.child {
    background: springgreen;
    width:calc(100% + 330px);
    padding: 0 0 0 20px;
    margin: 0 0 0 -20px;
}

https://jsfiddle.net/y166e3nb/3/

The calc() statement in each needs to be 2x the value of the padding.