有没有一种方法可以将一个flex/grid子项(超过三个)居中并且宽度不同? [英] Is there a way to center one of the flex/grid children(more than three) and with different widths?

查看:29
本文介绍了有没有一种方法可以将一个flex/grid子项(超过三个)居中并且宽度不同?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

查看代码段.有一条红线显示父中心.有没有一种方法可以使中间块水平居中?CSS网格解决方案也将起作用.

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.

我可以想象2种解决方案:

I can imagine 2 solutions:

  • 位置:绝对
  • 用相同宽度的包装纸包裹2个左块和2个右块

但我对其中任何一个都不满意.

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:这不是此问题的重复项,因为我正在尝试为任何数量的孩子提供解决方案.我提到了第二个解决方案,供3个孩子使用.

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.

推荐答案

目前无法实现.

目前,有 NO ,Flexbox,CSs-Grid或任何其他布局方法或算法可以使元素居中,而无需考虑同级元素的大小.

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.

您将需要Javascript来调整边距或重新排列HTML结构以适应您的设计选择.

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

可以使用绝对定位来使特定元素居中(尽管您已经排除了这种情况),但这完全忽略了其他同级,因此位置"可能会受到影响,我们再次依靠JS是必需的.

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.

这篇关于有没有一种方法可以将一个flex/grid子项(超过三个)居中并且宽度不同?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆