创建一个容器,其中包含一个简单的 box 元素,后续将使用它来演示这些居中方法。
这是 HTML:
<article>
<div></div>
</article>
这是我们的起始 CSS:
article {
width: 100%;
min-height: 100vh;
background: black;
display: grid;
}
div {
width: 200px;
background: yellow;
height: 100px;
}
现在,让我们看一下将 div 居中的各种方法。
我最喜欢使用 Grid 让元素居中。
将div 居中:
article {
display: grid;
}
div {
place-self: center;
}
article {
width: 100%;
min-height: 100vh;
background: black;
display: grid;
}
div {
width: 200px;
background: yellow;
height: 100px;
place-self: center; /* new */
}
body {margin: 0;}
现在使用 Grid 将我们的 div 居中。
设置属性的方法有很多,但在这里将其设置为 justify-content:
center
align-items: center
垂直对齐。
article {
display: grid;
justify-content: center;
align-items: center;
}
article {
width: 100%;
min-height: 100vh;
background: black;
display: grid;
justify-content: center; /* new */
align-items: center; /* new */
}
div {
width: 200px;
background: yellow;
height: 100px;
}
body {margin: 0;}
此方法的一个明显优点是它涉及的代码较少,因为居中由容器处理。但在某些方面,通过其容器定位 div 也是一个缺点,容器中的任何其他元素都会受其影响。将div 分配为自动边距。这使得浏览器自动计算子 div 周围的可用空间,并将其垂直和水平划分,将 div 放在中间:display: grid;
margin: auto
article {
display: grid;
}
div {
margin: auto;
}
article {
width: 100%;
min-height: 100vh;
background: black;
display: grid;
}
div {
width: 200px;
background: yellow;
height: 100px;
margin: auto; /* new */
}
body {margin: 0;}
它可以通过定位容器来使我们的 div 居中:place-items
article {
display: grid;
place-items: center;
}
article {
width: 100%;
min-height: 100vh;
background: black;
display: grid;
place-items: center; /* new */
}
div {
width: 200px;
background: yellow;
height: 100px;
}
body {margin: 0;}
这些方法中的每一种都可以让DIV在容器内水平和垂直地居中。