css居中问题总结
发布时间:2017-08-18, 17:16:10 分类:HTML | 编辑 off 网址 | 辅助
正文 2182字数 39,944阅读
html代码:<div class="box">
<div class="box-item">
文字
</div>
</div>code
Run code
Cut to clipboard
css样式:
一、水平居中
.box-item{
text-align:center;
}code
Run code
Cut to clipboard
*一般用于文字以及inline-block/inline水平居中 ,设置该值表示box-item内文字居中对齐
.box-item{
margin:0 auto;
}code
Run code
Cut to clipboard
*一般用于类似div的block水平居中,表示box-item整个div在box内水平居中对齐
二、垂直居中
高度等于行高,适合单行文字居中对齐
.box-item{
line-height:30px;
height:30px
} code
Run code
Cut to clipboard
margin为高度一半
.box{
width:100%;
height:100%;
margin:0;
padding:0
}
.box-item{
width:100px;
height:100px;
border:1px solid #ccc;
position:relative;
top: 50%;
margin: -150px auto 0 auto;
}
Run code
Cut to clipboard
前一种方式的改良版
.box{
width:100%;
height:100%;
margin:0;
padding:0
}
.box-item{
width:100px;
height:100px;
border:1px solid #ccc;
position:relative;
top: 50%;
margin:0 auto;
transform: translateY(-50%);
}
Run code
Cut to clipboard
align-items存在兼容性问题
.box {
display: flex;
align-items: center;
justify-content: center;
}
.box-item {
width: 300px;
height: 300px;
border: 1px solid #ccc;
}
Run code
Cut to clipboard
兼容性较好的几种:
.box-item{
margin:auto;
width:100px;
height:100px;
position:absolute;
top:0;
left:0;
bottom:0;
right:0;
}
Run code
Cut to clipboard
.box{
position: relative;
height:100%;
width:100%;
}
.box-item{
width: 100px;
height: 100px;
overflow: auto;
margin: auto;
position: absolute;
top: 0; left: 0; bottom: 0; right: 0;
}
Run code
Cut to clipboard
.box{
text-align: center;
overflow: auto;
height:100%;
}
.box:after,.box-item{
display: inline-block;
vertical-align: middle;
}
.box:after {
content: '';
height: 100%;
margin-left: -0.25em;
}
.box-item{
max-width: 99%;
}
Run code
Cut to clipboard
表格法
.box{
display:table;
width:100%;
height:100%;
}
.box-item {
display: table-cell;
vertical-align: middle;
text-align: center;
}
Run code
Cut to clipboard
(支付宝)给作者钱财以资鼓励 (微信)→
标签: 居中4
暂无评论 »