how to make a text ele to the right of a left floated ele automatically occupy the rest width?
Tags: css
Problem :
<div style="width:<?php echo $w; ?>">
<div style="float:left;margin-right:10px;width:200px">whatever</div>
<h2 style="border-bottom:solid 1px black">title</h2>
</div>
By default, the width of h2
would be $w
, and the bottom border will strike the inner div, I want the h2 to automatically occupy the rest width, no matter what $w
's value is, the h2's width should be $w - 200 - 10
. How to achieve this in pure CSS?
PS: if I set css h2{float:left}
, h2's width would depend on its inner text's length. To have the h2
element occupy the rest of the width (so that I can have a beautiful bottom border) I have to manually set a width value for h2, which is what I'm trying to avoid.
Solution :
From the spec,
The border box of a table, a block-level replaced element, or an element in the normal flow that establishes a new block formatting context (such as an element with 'overflow' other than 'visible') must not overlap the margin box of any floats in the same block formatting context as the element itself.
Therefore, you can just add
h2 {
overflow: hidden;
}
div {
width: 500px; /* $w */
}
div > div {
float: left;
margin-right: 10px;
width: 200px;
}
h2 {
border-bottom: solid 1px black;
overflow: hidden;
}
<div>
<div>whatever</div>
<h2>title</h2>
</div>
You may also want to style the outer div
with overflow: hidden
just in case the floated element is taller than the h2
.