绝对定位元素水平垂直居中的两种常见方法

    xiaoxiao2022-05-25  219

    一、负外边距

    方法:绝对定位元素的尺寸已知,top设置为50%,left设置为50%,外边距margin取负数,大小是宽度width和高度height的一半,有内边距padding时要加上padding值再取半。具体代码如下:

    html代码:

    <div class="box"> <div class="box1"></div> </div>

    css代码:

    .box{ position: relative; width: 200px; height: 200px; background: yellow; } .box1{ position: absolute; top: 50%; left:50%; background: red; width: 100px; height: 100px; padding: 10px; margin-top: -60px; margin-left: -60px; }

    浏览器显示如下:

    除了这种常用方法外,在网上还看到了另一种比较简便的方法,整理如下:

    二、利用margin: auto实现居中

    方法:设置绝对定位元素top和bottom的值相等,left和right的值相等。但是left和right的值不能超过其相对元素width减去它自身width的一半,否则绝对定位会优先选取left值进行定位。top和bottom无此限制。最好配合overflow:auto防止溢出。具体代码如下:

    css代码:

    .box1{ position: relative; top: 0; bottom: 0; left: 0; right: 0; margin: auto; width: 100px; height: 100px; background: red; overflow: auto;//当内部内容较多时,会自动出现滚动条 }

    浏览器显示同上。

    相关资源:七夕情人节表白HTML源码(两款)

    最新回复(0)