【问题标题】:Centering grid child regardless of siblings width无论兄弟姐妹的宽度如何,居中网格孩子
【发布时间】:2019-10-03 02:01:36
【问题描述】:

我有一个带有 3 个孩子的 CSS 网格容器,它们的宽度都不同。我希望 2 侧的孩子位于容器的 2 侧,中间的孩子位于容器的中心。

我尝试将第一个设置为justify-self: start,将中间的设置为justify-self: center;,将最后一个设置为justify-self: end;,但它没有居中,它只是平均划分空间。

.container {
	display: grid;
	grid-template-columns: auto auto auto;
	height: 100px;
}
.first {
	justify-self: start;
	background-color: red;
	width: 50px;
}
.middle {
	justify-self: center;
	background-color: green;
	width: 70px;
}
.last {
	justify-self: end;
	background-color: blue;
	width: 200px;
}
<div class="container">
  <div class="first"></div>
  <div class="middle">Center me</div>
  <div class="last"></div>
</div>

我错过了什么吗?这不可能吗?

【问题讨论】:

  • 所以你希望列之间的间隙不相等?
  • 是的,我希望它居中,即使这意味着不相等的间隙
  • 这里是带有 flexbox 的:stackoverflow.com/a/55393886/8620333(带有网格,只需将 auto 替换为 1fr)
  • 问题在于渲染引擎不知道将中心列对齐什么。没有关于兄弟元素的“中心”概念,只有父元素。
  • flexbox 解决方案:stackoverflow.com/questions/43211390

标签: html css css-grid


【解决方案1】:

您可以将网格用于外部元素,并使用绝对位置将中间元素居中,并进行如下变换:

.container {
  display: grid;
  grid-template-columns: auto auto;
  height: 100px;
  position:relative;
  width:100%;
}
.first {
  justify-self: start;
  background-color: red;
  width: 50px;
}
.middle {
  background-color: green;
  width: 70px;
  position:absolute;
  left: 50%;
  transform: translateX(-50%);
  height:100%;
}
.last {
  justify-self: end;
  background-color: blue;
  width: 200px;
}
<div class="container">
  <div class="first"></div>
  <div class="middle">Center me</div>
  <div class="last"></div>
</div>

但请注意,使用此方法元素可能会重叠。

【讨论】:

    【解决方案2】:

    使用1fr 而不是auto,因为您明确定义了元素的宽度

    .container {
      display: grid;
      grid-template-columns: 1fr 1fr 1fr;
      height: 100px;
      /* The center */
      padding-bottom: 5px;
      background: linear-gradient(black, black) bottom center/5px 5px no-repeat;
    }
    
    .first {
      justify-self: start;
      background-color: red;
      width: 50px;
    }
    
    .middle {
      justify-self: center;
      background-color: green;
      width: 70px;
    }
    
    .last {
      justify-self: end;
      background-color: blue;
      width: 200px;
    }
    <div class="container">
      <div class="first"></div>
      <div class="middle">Center me</div>
      <div class="last"></div>
    </div>

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2019-08-21
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-06-04
      • 1970-01-01
      • 2018-12-12
      • 1970-01-01
      相关资源
      最近更新 更多