Search code examples
htmlcsscss-positionmargin

Align max-width aligned right with max-width margin auto in css


I am trying to achieve the following align effect between divs.

enter image description here

The blue box has to occupy the same width as the red boxes, but also the auto margin-right. This way, if the screen is resized reds and blues will be always aligned.

Is there any way to achieve that in CSS?

I tried to apply margin-left on the blue, also display a grid with grid-template-column: auto 1fr auto; but seems like it is not working because I can't get the auto margin.

I am adding a codepen to help people to see the problem and test.

https://codepen.io/Raikish/pen/BaWoexV

<div class="centered red"></div>
<div class="centered red"></div>
<div class="right blue"></div>
.centered {
  max-width: 500px;
  margin-left: auto;
  margin-right: auto;
}

.right {
  margin-left: auto;
  max-width: 1000px
}

div {
  margin-bottom: 10px;
  height : 200px;
}

.red {
  background-color: red;
}

.blue {
  background-color: blue;
}

Solution

  • Try this :

    .right {
      margin-left: calc(50% - 250px);
      max-width: 1000px
    }
    

    enter image description here