Using CSS flex I'm trying to get all inline elements centered except one inline element to align on the right. I do not want to extend the size of the boxes or change anything in regards to their vertical axis. I've not been able to get any further than what this CSS Flexbox generator can produce on it's own. If I add margin-left
on the last element then all the other elements align to the left. After that point if I add margin-left: auto;
and margin-right: auto;
to all of the other elements they spread out. The fact that the distinction between horizontal and vertical does not help.
How do I keep the first three elements to remain grouped and centered and only change the horizontal layout of the last element to be aligned to the right? I would prefer to be able to still use margin-right: 2px;
to not have it immediantly up against the border of .parentNode.parentNode
<header>
<span>Item 1</span>
<span>Item 2</span>
<span>Item 3</span>
<span>Item 4</span>
</header>
A visual demonstration of what I'm trying to achieve:
To center out item horizontally we use the justify-content: center; . The justify-content property allows us to position items along the main axis of the flex container.
The align-self property is a sub-property of the Flexible Box Layout module. It makes possible to override the align-items value for specific flex items.
align-items and justify-content are the important properties to absolutely center text horizontally and vertically. Horizontally centering is managed by the justify-content property and vertical centering by align-items.
You can use absolute positioning.
header {
display: flex;
justify-content: center;
border: 1px solid black;
}
span {
border: 1px solid black;
width: 100px;
height: 100px;
}
span:last-child {
position: absolute;
right: 2px;
}
<header>
<span>Item 1</span>
<span>Item 2</span>
<span>Item 3</span>
<span>Item 4</span>
</header>
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With