Solution 1: Using Flex
I would recommend using flex
and justify-content: space-between
the only drawback for using it would be if you are supporting older browsers such IE10- then you can check https://caniuse.com/#search=flex for more info.
As for space-between
is simple as according to MDN
The items are evenly distributed within the alignment container along the main axis. The spacing between each pair of adjacent items is the same. The first item is flush with the main-start edge, and the last item is flush with the main-end edge.
Meaning, it will have a first child aligned to the beginning of the parent and the last child aligned to the end and the remaining space is divided equally among the rest of the children if they exist, which will give you the desired layout if the img
is always the last child, no matter how many child div
s exist.
Personally, I would find using flex
is the most convenient and one of the cleanest ways to "position" and "layout" different elements across the page.
You can find the code below and a working fiddle here
HTML
<ol class="step-list">
<li class="step">
<p>Step 1</p>
<img src="https://placehold.it/150x150?text=Step1" alt="">
</li>
<li class="step">
<p>Step 2</p>
</li>
<li class="step">
<p>Step 3</p>
</li>
<li class="step">
<p>Step 4</p>
<img src="https://placehold.it/150x150?text=Step4" alt="">
</li>
</ol>
CSS
.step-list {
list-style: none;
}
.step {
display: flex;
justify-content: space-between;
}
Solution 2: Using Float
You can also still be using float
but in that case you will need to clear the p
instead of the img
and float it too.
Since all of the element of the containing elements are floated it is important to add a clearfix
to the li
tag not to collapse to nothing you can find more info here.
So your code would like this and you can find a working fiddle here
HTML
<ol class="step-list">
<li class="step">
<p>Step 1</p>
<img src="http://placehold.it/150x150?text=Step1" alt="">
</li>
<li class="step">
<p>Step 2</p>
</li>
<li class="step">
<p>Step 3</p>
</li>
<li class="step">
<p>Step 4</p>
<img src="http://placehold.it/150x150?text=Step4" alt="">
</li>
</ol>
CSS
.step-list {
list-style: none;
}
.step img {
float: right;
}
.step p {
float: left;
}
/*This is what is called a clearfix solution, for the floating problem*/
.step::after {
content: "";
display: block;
clear: both;
}
Don't hesitate to ask me any more questions if anything unclear.