-1

Have a look at the snippet. There is a red line to show center of the parent. Is there a way to horizontally center middle block ? CSS-grid solution will also work.

I can imagine 2 solutions:

  • position: absolute
  • wrap 2 left blocks and 2 right blocks with wrappers of same width

But I'm not happy with any of them.

.wrapper {
  display: flex;
  align-items: center;
  justify-content: space-between;
  
  height: 100px;
  padding: 5px;
  
  position: relative;
  background: teal;
  
  color: #fff;
  font-family: sans-serif;
  text-align: center;
  
  box-sizing: border-box;
}

.wrapper > div {
  padding: 10px;
  border: 3px solid white;
}

.wrapper::before {
  content: "";
  display: block;
  
  width: 2px;
  height: 100%;
  
  position: absolute;
  left: 50%;
  transform: translateX(-50%);
  background-color: red;
}

.centered {
  position: relative;
}

.centered::before {
  content: "";
  display: block;
  
  width: 2px;
  height: 100%;
  
  position: absolute;
  left: 50%;
  top: 0;
  transform: translateX(-50%);
  background-color: yellow;
}
<div class="wrapper">
  <div style="width:20px">L</div>
  <div style="width:10px">L</div>
  <div class="centered" style="width:20%">center</div>
  <div style="width:80px">R</div>
  <div style="width:10px">R</div>
</div>

PS: It's not a duplicate of this question, because I am trying to get a solution for any number of children. I mentioned solution for 3 children as a second one.

flppv
  • 4,111
  • 5
  • 35
  • 54
  • **Mod Note:** no need for more discussion here. There's a lot of flags and the discussion is getting emotional. When this happens, please all parties disengage. –  Sep 17 '19 at 12:00

2 Answers2

0

This is not currently possible.

At present there is NO, Flexbox, CSs-Grid or any other layout method or algorithm that allows for centering an element without taking the size of sibling elements into consideration.

You will require Javascript to adjust margins or re-arrange your HTML structure to accomodate your design choices.

It IS possible to center the specific element using absolute positioning (although you have ruled this out) but this ignores the other siblings completely thus their "positions" might be affected and we again fall back on JS being required.

Paulie_D
  • 107,962
  • 13
  • 142
  • 161
-1

You could use css grid:

.wrapper {
  display: grid;
  grid-template-columns: repeat(5, 1fr);
  justify-items: center;
  align-items: center;
}
demkovych
  • 7,827
  • 3
  • 19
  • 25