我想在CSS网格中居中放置项目,但这似乎是不可能的。如果没有更多项目,如何使最后一个项目在页面上居中。
复制:
* {
margin: 0;
padding: 0;
box-sizing: border-box;
}
body {
font-family: sans-serif;
width: 100%;
}
.post-grid {
width: 100%;
display: grid;
grid-column-gap: 1rem;
grid-row-gap: 1rem;
grid-template-columns: 1fr;
align-items: flex-start;
grid-template-columns: 1fr 1fr 1fr;
box-sizing: border-box;
}
.post {
position: relative;
box-shadow: 0 10px 30px rgba(65, 131, 135, 0.19);
background: #ccc;
flex-direction: column;
overflow: hidden;
transition: all 0.3s;
vertical-align: top;
height: 150px;
display: flex;
align-items: center;
justify-content: center;
padding: 20px;
}
<!DOCTYPE html>
<html>
<head>
<title>Parcel Sandbox</title>
<meta charset="UTF-8" />
<link rel="stylesheet" href="src/styles.css" media="all" />
</head>
<body>
<div class="post-grid">
<div class="post"></div>
<div class="post"></div>
<div class="post"></div>
<div class="post">I want this square in the middle of the page</div>
</div>
</body>
</html>
答案 0 :(得分:3)
grid-column CSS的简写属性通过在网格位置中添加一行,一个跨度或不添加任何内容(自动)来指定网格项目在网格列中的大小和位置,从而指定inline-start和inline-end网格区域的边缘。
:last-of-type CSS伪类表示一组同级元素中该类型的最后一个元素。
* {
margin: 0;
padding: 0;
box-sizing: border-box;
}
body {
font-family: sans-serif;
width: 100%;
}
.post-grid {
width: 100%;
display: grid;
grid-column-gap: 1rem;
grid-row-gap: 1rem;
grid-template-columns: 1fr;
align-items: flex-start;
grid-template-columns: 1fr 1fr 1fr;
box-sizing: border-box;
}
.post {
position: relative;
box-shadow: 0 10px 30px rgba(65, 131, 135, 0.19);
background: #ccc;
flex-direction: column;
overflow: hidden;
transition: all 0.3s;
vertical-align: top;
height: 150px;
display: flex;
align-items: center;
justify-content: center;
padding: 20px;
}
.post:last-of-type{
grid-column: 2 / 3;
}
<div class="post-grid">
<div class="post"></div>
<div class="post"></div>
<div class="post"></div>
<div class="post">I want this square in the middle of the page</div>
</div>