温馨提示×

温馨提示×

您好,登录后才能下订单哦!

密码登录×
登录注册×
其他方式登录
点击 登录注册 即表示同意《亿速云用户服务条款》

css实现垂直居中的方法有哪些

发布时间:2020-10-20 16:46:21 来源:亿速云 阅读:116 作者:小新 栏目:web开发

小编给大家分享一下css实现垂直居中的方法有哪些,希望大家阅读完这篇文章后大所收获,下面让我们一起去探讨吧!

html结构

<p class="box box2">
    <span class="content content2">垂直居中</span></p>

默认css样式结构

.box{
    width:200px;
    height:200px;
    background-color:green;   
}
.content{
    background-color:yellow;   
}

1. table-cell    

该方法兼容IE8+,火狐,谷歌,并且content是否有宽高都可以。  注:IE8+ 包含 IE8

.box2{
    display:table-cell;      //此元素会作为一个表格单元格显示(类似 <td> 和 <th>)
    text-align:center;       //左右居中
    vertical-align:middle;   //上下居中        
}

css实现垂直居中的方法有哪些

2. display: flex;      

该方法不兼容IE8,IE9content是否有宽高都可以。兼容火狐、谷歌

参考flex布局:https://www.cnblogs.com/qingchunshiguang/p/8011103.html

.box2{
    display: flex;
    justify-content:center;  //左右居中
    align-items:center;      //上下居中
}

css实现垂直居中的方法有哪些

3. 绝对定位和负边距      

该方法兼容IE8+,火狐,谷歌,content必须有宽高

.box2{
    position:relative;
}
.content2{
    position:absolute;
    top:50%;
    left:50%;
    margin-top:-40px;
    margin-left:-40px;
}

4. 绝对定位和0      

该方法兼容IE8+,火狐,谷歌,content必须有宽高。

.box2{
    position:relative;
}
.content2{
    margin:auto;
    position:absolute;
    top:0;
    left:0;
    right:0;
    bottom:0;
}

5. 绝对定位和transform    

该方法不兼容IE8,兼容IE9+,火狐,谷歌,content是否有宽高都可以。

.box2{
    position:relative;
}
.content2{
    position:absolute;
    top:50%;
    left:50%;
    transform:translate(-50%,-50%);
}

6. display:flex 和 margin:auto      

content有宽高:不兼容IE8,IE9,content没有宽高:不兼容IE。有无宽高都兼容火狐、谷歌。

.box2{
    display: flex;
    text-align: center;
}
.box2 .content2{margin: auto;}

看完了这篇文章,相信你对css实现垂直居中的方法有哪些有了一定的了解,想了解更多相关知识,欢迎关注亿速云行业资讯频道,感谢各位的阅读!

向AI问一下细节

免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。

css
AI