作为前端猴子,无论何时进行面试或工作,我们都会或多或少地遇到“使用CSS居中”的效果。今天,我将写一篇关于CSS垂直和水平居中方法的文章。
margin: 0 auto;
块级元素使用边距: 0 Auto;在父元素中间居中,但请记住要设置块级元素的宽度和高度。HTML部分
CSS
CSS部分
.example1 {
width: 200px;
height: 200px;
background-color: orange;
}
.example1 p {
width: 100px;
height: 100px;
background-color: red;
margin: 0 auto;
line-height: 100px;
text-align: center;
}
位置元素已知宽度绝对定位+边距反向偏移
.wrap { position: relative; background-color: orange; width: 300px; height: 300px; } .example2 { background-color: red; width: 100px; height: 100px; position: absolute; left: 50%; top: 50%; margin: -50px 0 0 -50px; }
如果元素未知宽度,则对变换元素未知宽度进行定位,只需替换空白:– 50px 0 0 – 50px;在上面的example2中,具有:转换:转换(-50%,-50%);
与上述HTML相同,并附加了CSS代码
.warp {
background-color: #FF8C00;
width: 200px;
height: 200px;
display: flex;
Justify content: Center; / * center sub items horizontally*/
Align items: Center; / * center sub items vertically*/
}
.example3 {
background-color: #F00;
width: 100px;
height: 100px;
}
另一个是表格单元格布局,因为我不想介绍,所以我不会介绍它。
使用绝对布局的Div,设置margin:auto; 并将top,left,right和bottom的值设置为相等,但并非所有值都必须为0。HTML部分
Center display
CSS部分
.warp {
position: relative;
background-color: orange;
width: 200px;
height: 200px;
}
.example3 {
position: absolute;
top: 0;
left: 0;
right: 0;
bottom: 0;
background-color: red;
width: 100px;
height: 100px;
margin: auto;
}
.warp {
position: relative;
background-color: orange;
width: 200px;
height: 200px;
}
.example3 {
position: relative;
top:50%;
transform:translateY(-50%);
background-color: red;
width: 100px;
height: 100px;
margin: 0 auto;
}
使用内联块垂直对齐:中间伪元素之后的对齐效果更好。中间块的大小可用于包装和自适应内容,并且兼容性非常好。缺点是水平中心需要考虑内联块间隔中的空白
.warp {
text-align: center;
overflow: auto;
width: 200px;
height: 200px;
background-color: orange;
}
.example3 {
display: inline-block;
background-color: red;
vertical-align: middle;
width: 100px;
height: 100px;
}
.warp:after {
content: '';
display: inline-block;
vertical-align: middle;
height: 100%;
margin-left: -0.25em;
/* To offset spacing. May vary by font */
}
Flexbox布局。这是布局的终极方法,专门解决各种布局定位问题!优点:可以解决各种布局问题
.warp {
display: -webkit-flex;
display: -moz-box;
display: -ms-flexbox;
display: -webkit-box;
display: flex;
-webkit-box-align: center;
-moz-box-align: center;
-ms-flex-align: center;
-webkit-align-items: center;
align-items: center;
-webkit-box-pack: center;
-moz-box-pack: center;
-ms-flex-pack: center;
-webkit-justify-content: center;
justify-content: center;
width: 200px;
height: 200px;
background-color: orange;
}
.example3 {
width: 100px;
height: 100px;
background-color: red;
}
图片中间的例子1:
.warp {
width: 200px;
height: 200px;
background-color: orange;
display: flex;
align-items: center;
justify-content: center;
}
.example3 img {
width: 100px;
height: 100px;
background-color: blue;
}
本文介绍CSS3的示例代码,以实现水平中心,垂直中心和水平垂直中心。如果喜欢就点个关注点个赞吧,谢谢。
页面更新:2024-03-16
本站资料均由网友自行发布提供,仅用于学习交流。如有版权问题,请与我联系,QQ:4156828
© CopyRight 2020-2024 All Rights Reserved. Powered By 71396.com 闽ICP备11008920号-4
闽公网安备35020302034903号