0

I have this html+css:

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html>
<head>
  <title>Test</title>

  <style type="text/css">   

    body { border: 1px solid red; }    
    ul { float: left; }

  </style>
</head>


<body>
  <h1>Hello</h1> 
  <p>Testing test testing 1 2 3.</p>

  <ul>
     <li>Foobar</li>
  </ul>

</body>
</html>

Could someone explain to me why the list comes outside of the body border? And also how I can get it to... not... do that?

Screenshot

5 answers

2
points

You need to clear the floated ul, before the end of the 'page' add a clearing div after the ul, or use a clearfix solution:

http://perishablepress.com/press/2009/12/06/new-clearfix-hack/

Answered over 6 years ago by Tony Crockford
Rob 230
1
point

To answer your question "why?" the answer is parent elements are never to expand to contain floated elements. Floated elements are removed from the normal flow and this is why they can overflow their parent. To make the parent expand, there are several methods to "clear floats". Sometimes the easiest is just to add 'overflow:auto' to the parent but it may not always be the best.

Answered over 6 years ago by Rob
0
points

Because you are floating the UL unnecessarily. THE UL doesn't need to be floated here, so why do it?

Answered over 6 years ago by Robusto
  • I just removed everything else that wasn't part of the problem. In the real site the `ul` is a horizontal floating menu on the bottom of the page. over 6 years ago
0
points

Then give your UL a width and try it again.

EDIT: Meant this to be a comment to the above answer.

Answered over 6 years ago by Robusto
0
points

Its mostly because you are adding the border to the 'BODY' element of the page, the BODY is not really a container as such and should only really be used as something to build inside rather than with.

If you add a container around your content and take the float left off the UL (it dosen't need it) it will work as you want it to:

<div class="container">
  <h1>Hello</h1> 
  <p>Testing test testing 1 2 3.</p>

  <ul>
     <li>Foobar</li>
  </ul>
</div>

and change your css to just this:

.container {
border: 1px solid red;
}

if for some reason you really needed to add the float:left; to your UL then use the following html with the same css i've posted:

    <div class="container">
      <h1>Hello</h1> 
      <p>Testing test testing 1 2 3.</p>

      <ul>
         <li>Foobar</li>
      </ul>
    <div style="clear:both;"></div>

</div>

The div with the style clears the float so it dosen't hang over the edge of anything.

Answered over 6 years ago by richard bruce