CSS中水平居中和垂直居中的方法有哪些?写代码?
1。已知固定宽度和高度元素
.parent {
position: relative;
}
.child {
width: 300px;
height: 100px;
padding: 20px;
position: absolute;
top: 50%;
left: 50%;
margin: -70px 0 0 -170px;
}2。未知宽度和高度元素
.parent {
position: relative;
}
.child {
position: absolute;
top: 50%;
left: 50%;
transform: translate(-50%, -50%);
}3。使用 Flex 布局
.parent {
display: flex;
justify-content: center;
align-items: center;
}4。使用网格布局
.parent {
height: 140px;
display: grid;
}
.child {
margin: auto;
} 版权声明
本文仅代表作者观点,不代表Code前端网立场。
本文系作者Code前端网发表,如需转载,请注明页面地址。
code前端网