I would like to position some elements at different distances from the left border of a parent div
. Each element holds its own distance (in percentage of the width of the parent div
).
Since position
does not seem to be the right approach, I tried to do that by floating the element to the right
div {
display: flex;
flex-direction: row;
}
#root {
width: 50%;
border: solid;
}
#one {
float: right;
margin-left: 20%;
}
#two {
float: right;
margin-left: 80%;
}
<div id="root">
<div id="one">1</div>
<div id="two">2</div>
</div>
My expectation was that the first element would be at 10% of the div
width (so 5% of the page width, since the parent div
is 50% width relative to the page) and the second one at 80%. This is not the case, the docs mention that
Elements after a floating element will flow around it.
They also mention that clear
can be used to avoid this but I did not manage to make it happen (that is to make it so that each float is recalculated from the left border of the parent div
).
Is this something which is possible?
As a workaround I thought about calculating the float of the second element reltive to the first one, but that would horrendously(*) complicate my code so maybe there is a cleaner solution.
(*) For the case above that would be 80% - 20%
(the ones which are already floated) = 60%
. But even here the positionning is not correct (the 2
is too much to the right; there should be 20% blank, 1
, 40% blank, 2
, 20% blank - but the widths of the numbers themselves should be taken into account as well)
div {
display: flex;
flex-direction: row;
}
#root {
width: 50%;
border: solid;
}
#one {
float: right;
margin-left: 20%;
}
#two {
float: right;
margin-left: 60%;
}
<div id="root">
<div id="one">1</div>
<div id="two">2</div>
</div>