I am learning float property in CSS. But I have one doubt. I want that image and paragraph should float on left and right inside div.
I am not getting image and paragraph floated on left and right. Paragraph is starting just below the image. But I want that paragraph should be on right side on the div.
But when I reduced the content of the paragrah it is floating on right side. It is confusing for me.
Using
<p>This is simple text</p>
then it is floating on right side of container and if content of paragraph is large then it is not floating on right side.
* {
margin: 0;
padding: 0;
box-sizing: border-box;
}
div {
border: 2px solid red;
overflow: hidden;
}
img {
float: left;
border: 2px solid blue;
}
p {
float: right;
border: 2px solid cyan;
}
div::after {
content: "";
display: block;
clear: both;
}
<div>
<img src="challenges.jpg" width="250" height="250" />
<p>
Lorem ipsum dolor sit, amet consectetur adipisicing elit. Quod nesciunt quis rem autem cupiditate molestias reprehenderit quia iusto, perspiciatis repellendus ipsam esse voluptatum culpa labore omnis inventore voluptates non ducimus.
</p>
</div>
Reducing the content of paragraph then it is floating on right side and if I increase the content of paragraph then it is starting just below the image.
Why is it so?
4
Answers
To float img and paragraph tag inside div, img and P tag must have a width less than div. For example, in your case, when you increase content in P tag then p tag width increases as well. So try giving some fixed width like 300px etc to a paragraph p tag and it will work the way you want.
float: right
on the paragraph tag essentially made it not behave to the other floating inside the containerRemove the float property on the paragraph tag and increase the text content so that you can actually see the text wrap around down.
https://developer.mozilla.org/en-US/docs/Web/CSS/float – this has an interactive example you play around to see what’s actually happening.
If you want to align elements, I would suggest using flexboxes or grid to achieve the desired result. Floating elements does have it’s uses but it shouldn’t be misused.
Float is not used anymore, to be honest. Flexbox and Grid have taken over all the layout techniques previously used. Here is how you can achieve the same using flexbox.
HTML
CSS
With float, we can do something like this. You don’t have to use floats on both of them. Only the image will do. Or I think on some fixed dimension. For example, the image in this case.
If we use float: right on the image ( the image has to be inside the paragraph itself )
if we use float: left; on the image