How to shift the div on the right without moving the one on the left in a flexbox container?

Viewed 74

Here is my code:

<div class="flex-container fb-jc-center fb-ai-center">
  <div>
      first div
  </div>
  <div>
      second div
  </div>
</div>
.flex-container{
  display:flex;
  
}

.fb-jc-center{
  justify-content:center;
}
.fb-ai-center {
    align-items: center;
}

Example here: https://jsfiddle.net/0w1sk2au/

As you can see my two div are perfectly centered but I would like to shift the one on the right without moving the one on the left.

I tried:

.flex-container > div:nth-child(2){
    margin-left: 20px;
}

but it doesn't work because it moves the first div too.

I think I can add an empty element with a 20 px width:

<div class="flex-container fb-jc-center fb-ai-center">
  <div>
      first div
  </div>
  <div class="flex-container">
      <div id="empty"></div>
      <div>second div</div>
  </div>
</div>
#empty{
   width:20px;
}

Is there a simpler way to do it ?

1 Answers

To shift #red to the right without losing location for #blue, set rule margin-left for selector .flex-container > div.

The secret of this solution is to apply this css rule for both div, which means that the left margin of the #blue div is compensated.

Related