Centering grid child regardless of siblings width

情到浓时终转凉″ 提交于 2021-02-10 11:55:10

问题


I have a CSS grid container with 3 children, all with a different width. I want the 2 side children to be at the 2 sides of the container and the middle child to be at the center.

I tried setting the first one to justify-self: start, the middle one to justify-self: center;, and the last one to justify-self: end;, but it doesn't get centered, it just divides the space evenly.

.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>

Am I'm missing something? Is this not possible?


回答1:


You could use the grid for the outer elements and center the middle one using absolute position and transforms like so:

.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>

But be aware that elements could overlap using this method.




回答2:


Use 1fr instead of auto since you are explicitly defining the width of your elements

.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>


来源:https://stackoverflow.com/questions/56157586/centering-grid-child-regardless-of-siblings-width

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