I am trying to create a row of buttons which have increasing margin-left sizes.
For example:
[b1]--[b2]-----[b3]-------[b4]
let '-'
be whitespace. I couldn't figure out the formatting to have consecutive spaces on stackoverflow... As you can see, b1 will have a margin-left of 10%
, b2 20%
, b3 40%
and b4 80%
.
However, it looks like the margin-lefts are accumulating such that b2 will have a total margin-left of 30%
and b3 a total of 70%
and so on...
My objective is to have each button be positioned a certain distance away from the very left of the screen. I am trying to accomplish that by using margin-left. However, since the buttons are in the same div, I believe that makes the margin-left values accumulate and thus the next button's margin-left value will always be accumulated with the previous button's margin-left values.
That is just my conjecture on what's happening but the code is not doing what I have in mind: each button should be a certain distance away from the left. For example b1 should be 10%
from the left. b2 should be 20%
from the left. Essentially, I want all the button to start margin-left from the very beginning.
So here's the code. Please excuse any pseudocode as I'm typing this up here because I'm on another machine that doesn't have my sourcecode.
html:
<div class='outer'>
<div class='inner'>
<div class='buttons'>
<button>b1<button/>
<button>b2<button/>
<button>b3<button/>
<button>b4<button/>
</div>
</div>
</div>
css:
outer { width: 100% }
inner { width: 100% }
buttons { width: 100% }
b1 { margin-left: 10%}
b2 { margin-left: 20%}
b3 { margin-left: 40%}
b4 { margin-left: 80%}
What you are looking for is "position: absolute" (or "position: fixed" in some cases).
You can apply the "absolute" property to each of the buttons as shown below, this will make each buttons position absolute (i.e. not based on the position of the previous button, as in your example). You can read more about absolute positioning here: https://www.w3schools.com/css/css_positioning.asp
As you mentioned, your code is a little off in this example, so I will point out you are missing closing tags on your divs, your closing button tag is incorrect and your CSS syntax is off.
The below code should solve your issue:
.buttons button {position: absolute}
.b1 { margin-left: 10%}
.b2 { margin-left: 20%}
.b3 { margin-left: 40%}
.b4 { margin-left: 80%}
<div class='buttons'>
<button class='b1'>b1</button>
<button class='b2'>b2</button>
<button class='b3'>b3</button>
<button class='b4'>b4</button>
</div>
Please note: you can also replace "absolute" with "fixed" in the above example for the same effect. The "absolute" property will position it to the nearest positioned ancestor (i.e. if you were to re-position outer/inner divs), whereas "Fixed" will always be positioned relative to the view port.
Hope this helps!