失眠网,内容丰富有趣,生活中的好帮手!
失眠网 > html元素垂直水平居中显示 关于css:html-元素垂直水平居中

html元素垂直水平居中显示 关于css:html-元素垂直水平居中

时间:2023-05-16 09:29:46

相关推荐

html元素垂直水平居中显示 关于css:html-元素垂直水平居中

一、 不定宽高元素程度垂直居中

1、transform: translate()

程度垂直居中

.wrapper{

background-color:#eee;

height:200px;

}

.center{

position:relative;

width:300px;

padding:10px20px;

background-color:#2c3e50;

color:#fff;

left:50%;

right:50%;

transform:translate(-50%,-50%);

}

毛病:IE9以下不兼容

2、flex 布局,利用justify-content和align-items 实现居中

程度垂直居中

.wrapper{

height:200px;

background-color:#eee;

display:flex;

justify-content:center;

align-items:center;

}

.center2{

position:relative;

width:300px;

padding:10px20px;

background-color:#2c3e50;

color:#fff;

}

3、应用table+table-cell实现垂直居中,display:inline-block;或margin: auto;实现程度居中

程度垂直居中

.wrapper{

background-color:#eee;

height:200px;

width:100%;

display:table;

}

.content{

display:table-cell;

text-align:center;

vertical-align:middle;

}

.center3{

display:inline-block;

width:300px;

padding:10px20px;

background-color:#2c3e50;

color:#fff;

}

4、伪元素:after, :before 应用inline-block+ vertical-align:middle 对齐伪元素

程度垂直居中

.wrapper{

background-color:#eee;

height:200px;

width:100%;

position:relative;

}

.wrapper:after{

content:'';

display:inline-block;

vertical-align:middle;

height:100%;

}

.center4{

background-color:#2c3e50;

padding:10px20px;

color:#fff;

display:inline-block;

}

5、writing-mode: 扭转文字的显示方向

程度垂直居中

.wrapper{

background-color:#eee;

width:100%;

height:200px;

writing-mode:vertical-lr;

}

.content{

writing-mode:horizontal-tb;

display:inline-block;

width:100%;

}

.center5{

background-color:#2c3e50;

padding:10px20px;

color:#fff;

display:inline-block;

margin:auto;

text-align:left;

}

二、 固定宽高元素程度垂直居中

6、absolute+ 负margin

程度垂直居中

.wrapper {

background-color:#eee;

height:200px;

width:100%;

position:relative;

}

.center6{

background-color:#2c3e50;

color:#fff;

width:300px;

height:50px;

line-height:50px;

position:absolute;

top:50%;

left:50%;

margin-left:-150px;

margin-top:-25px;

}

设置相对定位,left:50%; top: 50%;使以后元素的左上角处于父元素的核心地位, 再利用负margin使其核心位于父元素的核心。

7、absolute+ 上下左右等值

程度垂直居中

.wrapper {

background-color:#eee;

height:200px;

width:100%;

position:relative;

}

.center7 {

background-color:#2c3e50;

color:#fff;

width:300px;

height:50px;

line-height:50px;

position:absolute;

top:0;

left:0;

right:0;

bottom:0;

margin:auto;

}

如果觉得《html元素垂直水平居中显示 关于css:html-元素垂直水平居中》对你有帮助,请点赞、收藏,并留下你的观点哦!

本内容不代表本网观点和政治立场,如有侵犯你的权益请联系我们处理。
网友评论
网友评论仅供其表达个人看法,并不表明网站立场。