Reputation: 2800
I have two div's:
<div><label for="1">Some really loooong text... Which breaks the second div. Which then appears shifted to the right.</label><input type="text" id="1" name"1"></div>
<div><label for="2">Shifted.</label><input type="text" id="2" name"2">
I use the following css to float the label left of the input text field:
label{
width:200px;
float:left;
}
The second div shifts to the left instead of appearing below the first one. It should be aligned to the left as the first one.
Here is the example: http://jsfiddle.net/qh37Y/
Now if I insert a clear:both; div it works, but is this best practice?
.clearer {
clear:both;
}
<div class="clearer"><label for="2">Shifted.</label><input type="text" id="2" name"2">
See here: http://jsfiddle.net/ywUx6/
Upvotes: 7
Views: 53921
Reputation: 191
I've noticed that the conventional solutions may not suffice if we are dealing with divs of the flex
display type. If you want to display a flex
div below a block, even if the block has width: 100%
or clear: both
is used, the flex still will appear to the side of it. The solution to this is to also specify the width of the flex element as 100%, as such:
CSS:
.top_div {
display: block;
}
.bottom_div {
display: flex;
justify-content: center;
width: 100%; /*key*/
}
HTML:
<div class="replies_container">Your block content</div>
<div class="flex_container">
Your flex content</div>
Side note: Perhaps this is not a direct solution to the OP's question but may be useful for future Googlers who may stumble across it (such as myself) .
Upvotes: 1
Reputation: 17732
It looks as though this is actually a problem with the height of the divs.
Since the content is floating, it doesn't affect the height of the div. Thus, the content in the second div (NOT the div itself) wraps around the floated label from the first div.
clear: both
is acceptable, but if (for instance), you wanted to use these divs as one column of a two-column layout, it would break the layout.
I would suggest div { overflow: hidden; }
instead. This supplies a new box-context for the divs, which disallows overlapping borders, thus making the height of floated contents contribute to the height of the div.
Edit: Fixed fiddle
Upvotes: 14
Reputation: 7955
First of all, you can't use identifiers which starts with digits - just sayin' ;)
If I understood your probledm, solution is to add clear: both
to your div:
div {
clear: both
}
Place the code under the label definition.
Upvotes: 5
Reputation: 4515
Yes, clear: both
is usually what you end up using. Note that you can also use clear: left
etc
Upvotes: 5