Div is centered in container with another element in container

Edit: I ended up doing Centering and right-aligning flexbox items Answer Michael_B Method # 2

So, I have a container that has two elements, a red and a green box (the width is not fixed). I would like the green box to be centered within the container, if possible. And when the red box is on the way, then the green square just sits next to it.

The only way I know how to do this is to set the red square as position: absolute

, but the problem is when the container gets too small, the green square overlaps the red.

I only support modern browsers (no IE) so flexboxes and other new stuff are welcome.

Thank.

Result

.wrapper {
  width: 600px;
  height: 100px;
  text-align: center;
  position: relative;
  border: 5px solid black;
}

.wrapper+.wrapper {
  margin-top: 20px;
}

.wrapper:nth-child(2) {
  width: 500px;
}

.wrapper:nth-child(3) {
  width: 410px;
}

.align-left {
  display: inline-block;
  position: absolute;
  left: 0;
  background-color: red;
  width: 100px;
  height: 100%;
  z-index: 0;
}

.centered {
  display: inline-block;
  background-color: green;
  width: 300px;
  height: 100%;
  // so the overlap is more visual
  z-index: 1;
  position: relative;
}
      

<div class="wrapper">
  <div class="align-left"></div>
  <div class="centered">
  </div>
</div>

<div class="wrapper">
  <div class="align-left"></div>
  <div class="centered">
  </div>
</div>

<div class="wrapper">
  <div class="align-left"></div>
  <div class="centered">
  </div>
</div>
      

Run codeHide result


https://jsfiddle.net/ft7z9za3/1/

+3


source to share





All Articles