Combining float and margin in CSS
Now our text is pressed against the image on the left side. Let's try to move this text a little. To do this, we'll give our paragraphs a left margin of 30px, and a red border for the parent div.
Unexpectedly, only the text that is adjacent to the parent image will move to the right, but the text adjacent to the image will not move:
<div>
<img src="img.png" alt="">
<p>
Lorem ipsum dolor sit amet, consectetur adipiscing elitorire.
</p>
<p>
some long text
</p>
</div>
div {
width: 400px;
border: 1px solid red;
text-align: justify;
}
p {
margin-left: 30px;
}
img {
float: left;
}
:
To understand why this is so, let's add a green border to the paragraphs:
<div>
<img src="img.png" alt="">
<p>
Lorem ipsum dolor sit amet, consectetur adipiscing elitorire.
</p>
<p>
some long text
</p>
</div>
div {
width: 400px;
border: 1px solid red;
text-align: justify;
}
p {
margin-left: 30px;
border: 1px solid green;
}
img {
float: left;
}
:
As we can see, the paragraphs are actually moved away from the left edge, but not from the image, but from the parent div. To take a closer look, let's also add semi-opacity to the image using the opacity property:
<div>
<img src="img.png" alt="">
<p>
Lorem ipsum dolor sit amet, consectetur adipiscing elitorire.
</p>
<p>
some long text
</p>
</div>
div {
width: 400px;
border: 1px solid red;
text-align: justify;
}
p {
margin-left: 30px;
border: 1px solid green;
}
img {
float: left;
opacity: 0.5;
}
:
Now it is clear that there is a reaction to margin-left, only the paragraphs are actually placed under the picture. Let's remove the indent, while leaving the picture translucent:
<div>
<img src="img.png" alt="">
<p>
Lorem ipsum dolor sit amet, consectetur adipiscing elitorire.
</p>
<p>
some long text
</p>
</div>
div {
width: 400px;
border: 1px solid red;
text-align: justify;
}
p {
border: 1px solid green;
}
img {
float: left;
opacity: 0.5;
}
:
This is what our paragraphs actually look like - their text is pushed aside by the picture, but physically the paragraphs are located under the picture, this can be seen by the border that starts from the left edge of the parent diva.
Let's return margin and stick the image in the first paragraph:
<div>
<p>
<img src="img.png" alt="">
Lorem ipsum dolor sit amet, consectetur adipiscing elitorire.
</p>
<p>
some long text
</p>
</div>
div {
width: 400px;
border: 1px solid red;
text-align: justify;
}
p {
margin-left: 30px;
border: 1px solid green;
}
img {
float: left;
opacity: 0.5;
}
:
Now the picture moves along with the paragraphs!