Is there a way to center one of the flex/grid children(more than three) and with different widths?

流过昼夜 提交于 2019-12-08 15:21:16

问题


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.


回答1:


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.




回答2:


You could use css grid:

.wrapper {
  display: grid;
  grid-template-columns: repeat(5, 1fr);
  justify-items: center;
  align-items: center;
}


来源:https://stackoverflow.com/questions/57972830/is-there-a-way-to-center-one-of-the-flex-grid-childrenmore-than-three-and-with

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!