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

Viewed 624

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;
}
2 Answers

Try this :

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

enter image description here

if you set the size to be half the viewport size (50vw) + half the element size (=250px), you'll get the correct max-width for the .right element. After that, you can simply use margin-left: auto for that element just as you used it for the .centered element.

https://codepen.io/thatkookooguy/pen/bGqVPEJ

body {
  margin: 0;
  padding: 0;
  --width: 500px;
  --half-width: calc(var(--width) / 2);
  --height: 50px;
}

.centered {
  max-width: var(--width);
  margin-left: auto;
  margin-right: auto;
}

.right {
  margin-left: auto;
  max-width: calc(50vw + var(--half-width));
}

.shared {
  margin-bottom: 10px;
  height: var(--height);
}

.red {
  background-color: red;
}

.blue {
  background-color: blue;
}
<div class="shared centered red"></div>
<div class="shared centered red"></div>
<div class="shared right blue"></div>

Related