Forum Moderators: not2easy

Message Too Old, No Replies

float and div problem

         

jake_pa2001

8:58 pm on Feb 10, 2010 (gmt 0)

10+ Year Member



Hi,
I'm trying to understand the basics of float, but I've found an example that leaves me completely at a loss.

Very simple scenario: two divs, one on top of the other:


<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en-gb" lang="en-gb" >
<head>

<meta http-equiv="content-type" content="text/html; charset=iso-8859-1" />

<title>float test 2</title>
<style type="text/css">

div.a {
width: 100px;
height: 100px;
background-color: blue;
float: left;
}

div.b {
/* width: 100px; */
/* height: 100px; */
background-color: red;
}

</style>

</head>
<body>

<div class="a">Some text in here</div>

<div class="b">Some more text in here</div>

</body>
</html>


This does what I would expect - the text of div b flows up beside div a and the background color too.

But if I add a width and height to div b, suddenly it stops floating up beside div a AND the background color disappears. This happens on IE and FF.

This code shows the problem:

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en-gb" lang="en-gb" >
<head>

<meta http-equiv="content-type" content="text/html; charset=iso-8859-1" />

<title>float test 5</title>
<style type="text/css">

div.a {
width: 100px;
height: 100px;
background-color: blue;
float: left;
}

div.b {
width: 100px;
height: 100px;
background-color: red;
}

</style>

</head>
<body>

<div class="a">Some text in here</div>

<div class="b">Some more text in here</div>

</body>
</html>

Does anyone know why?
Thanks!

CSS_Kidd

9:58 pm on Feb 10, 2010 (gmt 0)

10+ Year Member



Well it is just simply covering up div.b and pushing the text out. It is actually doing the same thing in the first example. By default a div will span the width of it's parent container. So in example one div.b is actually touching the left of the body while pushing the text (or any other content) aside from the floated div.a.

Here is a really good rundown on everything about float [smashingmagazine.com]

Other than that, you can do a couple of things to view the div.b in example 2.

add a margin: 100px; to div.b
or float it too.

jake_pa2001

10:30 pm on Feb 10, 2010 (gmt 0)

10+ Year Member



Thanks for your helpful reply. That article is great too.
This is what I didn't realize (from the article):

Non-positioned, non-floated, block-level elements act as if the floated element is not there, since the floated element is out of document flow.

Thanks!