css - 这个代码为什么能够水平和垂直都居中?

查看:126
本文介绍了css - 这个代码为什么能够水平和垂直都居中?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

问 题

margin:auto只能水平居中。
为什么设置了

position: absolute;
left: 0;
right: 0;
top: 0;
bottom: 0;
margin: auto;

就能够水平和垂直都居中呢?

<!DOCTYPE html>
<html>
    <head>
        <meta charset="UTF-8">
        <title></title>
    </head>
    <style type="text/css">
        #id{
            background: papayawhip;
            width: 200px;
            height: 200px;
            
            position: absolute;
            left: 0;
            right: 0;
            top: 0;
            bottom: 0;
        }
    </style>
    <body>
        <div id="id">
            
        </div>
    </body>
</html>

解决方案


1.尺寸限制(寬高有限制)
2.拉伸(有相反的方向屬性:如同時設定top和bottom,left和right)
3.margin:auto時
就會有絕對定位元素的絕對居中效果

Ps:ie8+支持

这篇关于css - 这个代码为什么能够水平和垂直都居中?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆