Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
815 views
in Technique[技术] by (71.8m points)

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

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>
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...