user1506145 user1506145 - 1 year ago 137
CSS Question

CSS increase width using calc() does not affect parent container

Take a look at the following snippet. How can I increase the width of the red container with 10px?

Is there a way to increase the width of an element in CSS, still affecting the parent container? Or do I have to use a pseudo-element placeholder to accomplish this instead?

<div style="
<div style="
width:calc(100% + 20px);
Inner container</div>

In the snippet above the blue container is not affected, and the red overflows.

Answer Source

Is there a way to increase width of an element by a certain amount, where the width of the element itself is not known until runtime?

You can only reliably do this using padding; however, padding will affect the layout of the element's contents, which may not be what you want. In your example, padding the child element will affect the layout of the text inside it; the content width is never really increased at all.

You can't change an element's content width by a definite amount when it is not known in advance and depends on external factors such as the amount of content it actually has, which is usually the case with floats, absolutely positioned elements, and inline-blocks. The closest you can get is an auto width, and that only has a meaningful effect on in-flow block boxes — which are none of the above — with respect to their parents, not their children.

In fact, the behavior that you see with calc(100% + 20px) is not governed by the spec, although it's as far as browsers generally go without falling into the cyclic dependency trap:

Specifies a percentage width. The percentage is calculated with respect to the width of the generated box's containing block. If the containing block's width depends on this element's width, then the resulting layout is undefined in CSS 2.1.

(calc() is CSS3, but the box model hasn't changed much from CSS2.1.)

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download