user3740970 user3740970 - 1 month ago 7
CSS Question

Why is the image overflowing outside of the wrapper?

I'm trying to clear the float with a div after the floated image but the image is still outside of the wrapper

This method to clearfix is usually effective - what am I doing wrong?

<!Doctype html>

<html>

<head>
<style>
#wrapper{
width:600px;
border: 2px solid black;
}

#wrapper p{
float:left;
width:200px;
margin-left:10px;
}

#wrapper img{
float:right;
}

#wrapper .clearfix{
overflow:auto;
border:none;
}
</style>
</head>

<body>
<div id="wrapper">

<p>
This image is taller than the element containing it, and it's floated, so it's overflowing outside of its container!
</p>

<img src="picture.jpg"/>

<div class="clearfix">
</div>

</div>
</body>

</html>

Answer

If you want to use an overflow method for clearing floats, then you should set overflow: auto; on your parent element.

Here is the codepen

HTML

<div id="wrapper">

  <p>
    This image is taller than the element containing it, and it's floated, so it's overflowing outside of its container!
  </p>

  <img src="picture.jpg" />

</div>

CSS

 #wrapper {
   overflow: auto;
   width: 600px;
   border: 2px solid black;
 }

 #wrapper p {
   float: left;
   width: 200px;
   margin-left: 10px;
 }

 #wrapper img {
   float: right;
 }