在 CSS 网格中将绝对定位的元素居中
Centering absolutely positioned element in CSS Grid
这支笔在 Mozilla 上有效。但是当我切换到 Chrome 时它就坏了。
是我的问题还是浏览器有问题?
.container {
height: 500px;
width: 500px;
background-color: beige;
display: grid;
grid-template-rows: 1fr;
grid-template-columns: 1fr;
}
.container h2 {
position: absolute;
justify-self: center;
align-self: center;
grid-row: 1;
grid-column: 1;
}
<div class="container">
<h2>TEXT</h2>
</div>
position: absolute
正在抛弃 Chrome(在 v62 上测试)。 Firefox 似乎将 justify-self
和 align-self
属性解释为覆盖,而 Chrome 不解释,因此行为不同。
只需删除 position: absolute
即可。
Chrome 似乎偏离了关于此问题的规范指南。
justify-self
和 align-self
属性 应该 在网格容器的绝对定位子元素上工作。
9.2. With a Grid Container as
Parent
An absolutely-positioned child of a grid container is out-of-flow and
not a grid item, and so does not affect the placement of other items
or the sizing of the grid.
The static position of an absolutely-positioned child of a grid
container is determined as if it were the sole grid item in a grid
area whose edges coincide with the padding edges of the grid
container.
Note that this position is affected by the values of justify-self
and align-self
on the child.
所以,Firefox 似乎有这个权利。
有关其他居中选项,请参阅此 post:
这支笔在 Mozilla 上有效。但是当我切换到 Chrome 时它就坏了。
是我的问题还是浏览器有问题?
.container {
height: 500px;
width: 500px;
background-color: beige;
display: grid;
grid-template-rows: 1fr;
grid-template-columns: 1fr;
}
.container h2 {
position: absolute;
justify-self: center;
align-self: center;
grid-row: 1;
grid-column: 1;
}
<div class="container">
<h2>TEXT</h2>
</div>
position: absolute
正在抛弃 Chrome(在 v62 上测试)。 Firefox 似乎将 justify-self
和 align-self
属性解释为覆盖,而 Chrome 不解释,因此行为不同。
只需删除 position: absolute
即可。
Chrome 似乎偏离了关于此问题的规范指南。
justify-self
和 align-self
属性 应该 在网格容器的绝对定位子元素上工作。
9.2. With a Grid Container as Parent
An absolutely-positioned child of a grid container is out-of-flow and not a grid item, and so does not affect the placement of other items or the sizing of the grid.
The static position of an absolutely-positioned child of a grid container is determined as if it were the sole grid item in a grid area whose edges coincide with the padding edges of the grid container.
Note that this position is affected by the values of
justify-self
andalign-self
on the child.
所以,Firefox 似乎有这个权利。
有关其他居中选项,请参阅此 post: