css样式水平垂直居中

css样式水平垂直居中

CSS 2024-02-09 07:00:06 1年以前

CSS样式中的水平垂直居中是Web开发中常见的技巧,它可以使元素在页面上居中显示,让页面更美观、易读、易操作。下面我们介绍一些实现水平垂直居中的CSS样式。

// 第一种方法: 把元素的 display 属性值设置为 table-cell 
.element {
display: table-cell;
vertical-align: middle;
text-align: center;
}
// 第二种方法: 使用绝对定位定位元素,然后设置 top、bottom 和 left、right 
.parent {
position: relative;
}
.child {
position: absolute;
top: 50%;
left: 50%;
transform: translate(-50%, -50%);
}
// 第三种方法: 使用 flexbox 布局 
.parent {
display: flex;
justify-content: center;
align-items: center;
}
// 第四种方法: 使用 grid 布局 
.parent {
display: grid;
place-items: center;
}
// 第五种方法: 使用 table 布局 
.parent {
display: table;
width: 100%;
height: 100%;
}
.child {
display: table-cell;
vertical-align: middle;
text-align: center;
}

以上就是实现水平垂直居中的一些常见CSS样式,不同的场景和需要可能使用不同的方式,但是以上提到的方法都是常用实用的。如果您想要使页面元素更好看、更美观更加优雅,请尝试使用上述方法实现水平垂直居中。

文章版权声明:除非注明,否则均为网络转载文章,转载或复制请以超链接形式并注明出处。