By default, an h2
is a block element, which means that it will take all the available horizontal space from its container. Therefore, using text-align: right
will just move the text inside it, but it will be occupying the same space, as you can see here:
.right {
float: right;
}
.right h2 {
background: cyan;
text-align: right;
}
.right img {
background: red;
float: left;
width: 100px;
height: 120px;
}
<div class="block right">
<h2>Header 2.1</h2>
<img src="images/wip.png" />
<p>Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod
tempor incididunt ut labore et dolore magna aliqua.</p>
</div>
Remove that text-align
property and add display: inline-block
to the h2
instead. Note display: inline
will also work, but the (vertical) margins and paddings will not be applied.
This will allow the floated image to push the h2
element in order to position itself at the beginning of the container:
.right {
float: right;
}
.right h2 {
background: cyan;
display: inline-block;
}
.right img {
float: left;
background: red;
width: 100px;
height: 120px;
}
<div class="block right">
<h2>Header 2.1</h2>
<img src="images/wip.png" />
<p>Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod
tempor incididunt ut labore et dolore magna aliqua.</p>
</div>
Another option is to move the img
in your HTML to be the first element:
.right {
float: right;
}
.right h2 {
background: cyan;
}
.right img {
float: left;
background: red;
width: 100px;
height: 120px;
}
<div class="block right">
<img src="images/wip.png" />
<h2>Header 2.1</h2>
<p>Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod
tempor incididunt ut labore et dolore magna aliqua.</p>
</div>