I've this simple html code, I want to know why the parent sibling div is influenced by the float css arrtibute. Is float is relative to the window not the block the element with float arrti in?
.floatLeft {
float:left;
}
<div >
<img class="floatLeft" src="https://i.sstatic.net/xdrQi.jpg?s=48&g=1"/>
<p>test</p>
</div>
<div>
<p>test1</p>
</div>
That's because the parent element collapses. See The great collapse.
The reason this happens, is because otherwise there would be virtually no way to wrap your text around your image. So the parent collapses to the minimum height required for its non-floated contents, and the next div just moves up, with its contents also respecting the float of the image. This way, you can easily create these kinds of text layouts, which would otherwise be hardly possible.
If you don't want this for whatever reason, you can clear the second div, so it doesn't float next to the image, there are multiple ways to do that, but a common one is to use a pseudo-element as a 'clearfix' element. The advantage of this solution is that you don't need any additional markup, apart from maybe an id or class to identify the element to be cleared.
In the example below, I just added a snippet of CSS which finds the first div, and styles the ::after pseudo-element so it is like you insert a cleared element after the contents of the first div.
This will force the first div to grow to below the image, and so the second div is forced fown.
You could add a class to the first div to select it, but for the sake of argument, I used the selector div:first-child::after, so I could leave the mark-up of your example completely untouched:
.floatLeft {
float:left;
}
div:first-child::after {
content: "";
display: block;
clear: both;
}
<div >
<img class="floatLeft" src="https://i.sstatic.net/xdrQi.jpg?s=48&g=1"/>
<p>test</p>
</div>
<div>
<p>test1</p>
</div>
For more information on the subjects of floats, including various ways to do the clear fix, see the excellent All about floats on CSS-tricks.com.
.floatLeft {
float:left;
}
.clear:after {
content: '';
display: block;
clear: both;
}
<div class="clear">
<img class="floatLeft" src="https://i.sstatic.net/xdrQi.jpg?s=48&g=1"/>
<p>test</p>
</div>
<div>
<p>test1</p>
</div>
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With