Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

CSS Flex all center except single right horizontally aligned element [duplicate]

Tags:

css

flexbox

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:

CSS Flex all horizontally centered except one element aligned right

like image 814
John Avatar asked Feb 02 '17 23:02

John


People also ask

How do you center flex items horizontally?

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.

What property allows you to override align items on individual flex items?

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.

Which flexbox property aligns items horizontally?

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.


1 Answers

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>
like image 66
Michael Coker Avatar answered Sep 24 '22 01:09

Michael Coker