Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to position div below another div

Tags:

css

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/

like image 256
jrn Avatar asked Jun 12 '12 19:06

jrn


2 Answers

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

like image 171
Ryan Kinal Avatar answered Sep 28 '22 06:09

Ryan Kinal


A clear:both div is perfectly acceptable to use.

like image 22
user1452058 Avatar answered Sep 28 '22 06:09

user1452058