![7896c46aecd33e867d32d11eb1294794.png](https://i-blog.csdnimg.cn/blog_migrate/37dbd8b5eeeadf5295a99d888b0d0f5d.png)
Web开发人员在日常生活中遇到许多需要将元素居中的实例。面试中问的也是非常普遍和重要的概念。因此,今天我想列出我最喜欢的三种使用CSS进行事物居中的方法。
![07d84f150940a19a6b7aa2718f990467.png](https://i-blog.csdnimg.cn/blog_migrate/ae5bcf9860844d3a4dcdd2ac3cce5d87.png)
我们有两个div元素,一个在另一个内部。外层div具有id ='container',内部容器具有id ='content'。在其中,我们有一个图标。
<div id="container">
<div id="content">
<i class="fa fa-beer" style="font-size:24px"></i>
</div>
</div>
![4e192581d1e8ba7db41a16e2841eb887.png](https://i-blog.csdnimg.cn/blog_migrate/8b8f953cabb2afc25c80c0a008a2c772.png)
1。使用Flexbox
我们可以使用flexbox将元素居中。为此,我们将显示属性分配给flex。对于居中项,我们使用属性justify-content和align-items并将其分配给center。
#container {
background: #eee;
height: 500px;
width: 100%;
display: flex;
justify-content: center;
align-items: center;
}
#content {
background: pink;
height: 100px;
width: 200px;
display: flex;
justify-content: center;
align-items: center;
}
2. 使用 Grid
使用网格将元素居中是一种更有效的方法。我们可以使用显示属性来利用网格。place-items属性用于使元素居中。
#container {
background: #eee;
height: 500px;
width: 100%;
position: relative;
display: grid;
place-items: center;
}
#content {
top: 50%;
background: pink;
height: 100px;
width: 200px;
display: grid;
place-items: center;
}
3.使用位置属性
另一种方法是使用位置属性使事物居中的老式方法。我们使用margin,top,right,bottom和left属性作为位置。
#container {
background: #eee;
height: 500px;
width: 100%;
position: relative;
}
#content {
top: 50%;
background: pink;
height: 100px;
width: 200px;
position: absolute;
left: 0;
bottom: 0;
right: 0;
top: 0;
margin: auto;
/* to align the icon */
text-align: center;
line-height: 120px;
}