Hitesh Kumar Hitesh Kumar - 1 month ago 6
CSS Question

CSS: flexbox first child to left and rest to center

I am playing with

flexbox
of CSS. I am trying to create a nav menu. I want the first item of the menu to be in the left most and rest of the item to be in the center. Currently I have everything in center. To align content in center I am using
justify-content: center
with container. But I dont know I can align a particualr item in
flex-box
. I tried to
float
it but since
float
are not meant for alignment and also float does not work with flexbox items. Is there any way/workaround to achieve this? Thanks. Here's the pen to play.

body{
background: #e0f080;
color: white;
font-weight: bold;
font-size: 1em;
}
.flex-container {
display: -webkit-flex;
display: flex;
background-color: tomato;
color: white;
font-weight: bold;
font-size: 1em;
justify-content: center;
}
.flex-item{
align-content: space-around;
margin: 10px;
border: 2px solid white;
padding: 5px;
}
.menu{
order: -1;
align-self: start;
font-size: 3em;
}


enter image description here

Answer

Use positioning - add position: relative to the flex-container and apply this to menu:

position: absolute;
top: 0;
left: 0;

I also removed one invalid property that you were using (align-self: start) to clean it up - demo below:

body {
  background: #e0f080;
  color: white;
  font-weight: bold;
  font-size: 1em;
}
.flex-container {
  display: -webkit-flex;
  display: flex;
  background-color: tomato;
  color: white;
  font-weight: bold;
  font-size: 1em;
  justify-content: center;
  position: relative;
}
.flex-item {
  align-content: space-around;
  margin: 10px;
  border: 2px solid white;
  padding: 5px;
}
.menu {
  order: -1;
  font-size: 3em;
  position: absolute;
  top: 0;
  left: 0;
}
<div class="flex-container">
  <div class="menu">
    <span>&#8801;<span>
  </div>
      
<a class="flex-item">item 1</a>
<a class="flex-item">item 2</a>
<a class="flex-item">item 3</a>
</div>

Comments