盒子水平垂直居中
文章目录
页面主体结构
总体 html 结构
<article>
<div></div>
</article>
css 结构
* {
margin: 0;
padding: 0;
}
html,
body {
width: 100%;
height: 100%;
}
article {
width: 100%;
height: 100%;
}
div {
width: 200px;
height: 150px;
background-color: skyblue;
}
盒子水平居中
margin
div {
margin: 0 auto;
}
text-align
article {
text-align: center;
}
div {
display: inline-block;
}
(缺点:article内部文字也会水平居中,需消除影响)
盒子垂直居中
transform
div {
position: absolute;
top: 50%;
transform: translateY(-50%);
/* 在知道div高度的情况下可以使用下面的方式代替上面一行 */
/* margin-top: -75px; */
}
盒子水平垂直居中
-
flex布局
article {
display: flex;
justify-content: center;
align-items: center;
}
-
grid布局
article {
display: grid;
grid-template-rows: 1fr 150px 1fr;
grid-template-columns: 1fr 200px 1fr;
}
div {
grid-area: 2 / 2 / 3 / 3;
}
- 绝对定位
div {
position: absolute;
top: 50%;
left: 50%;
transform: translate(-50%, -50%);
}
评论
登录后参与技术讨论,分享你的经验与见解。
登录 / 注册暂无评论