绝对定位后,position:absolute;不能使用margin: 0 auto;实现居中;

我们都知道margin: 0 auto;可也实现块状元素的水平居中;但是对于绝对顶为的元素就会失效;

请看实例:

复制代码
<!doctype html>
<html>
<head>
<meta charset="utf-8">
<title>绝对定位后margin: 0 auto;居中失效的解决方法</title>
<style type="text/css">
    .test-out {

         500px;
        height: 500px;
        margin: 0 auto; /*实现父元素居中*/
        background: red;
    }
    .test-in {
         200px;
        height: 200px;
        margin: 0 auto; /*实现子元素居中*/
        background: blue;
    }
        
</style>
</head>

<body>
<div class="test-out">
    <div class="test-in"></div>
</div>
</body>
</html>
复制代码

浏览器效果图:

我们可以看出在正常情况下: margin: 0 auto; 实现居中真是棒棒的!

我们把css样式修改为:

复制代码
<style type="text/css">
    .test-out {
        position: relative; /*作为子元素的 定位包含框,使子元素在父元素内 进行定位*/
         500px;
        height: 500px;
        margin: 0 auto; /*实现父元素居中*/
        background: red;
    }
    .test-in {
        position: absolute;  /*子元素实现绝对定位*/
         200px;
        height: 200px;
        margin: 0 auto;/* 此时会失效*/
        background: blue;
    }
复制代码

浏览器效果:

子元素(蓝色盒子)的居中效果已失效!

绝对定位以后margin: 0 auto;实现居中失效的解决方法:

为了使子元素(蓝色盒子)在绝对定位下实现居中,我们可以利用定位和margin-left取相应的负值,实现居中;

具体代码如下:

复制代码
<style type="text/css">
    .test-out {
        position: relative; /*作为子元素的 定位包含框,使子元素在父元素内 进行定位*/
         500px;
        height: 500px;
        margin: 0 auto; /*实现父元素居中*/
        background: red;
    }
    .test-in {
        position: absolute;  /*子元素实现绝对定位*/
        top: 0;
        left: 50%; /*先定位到父元素(红盒)的中线,然后使子元素(红盒)的外边界 左偏移, 半个子元素(红盒) 的宽度,即可*/
        margin-left: -100px;/*向左 偏移元素的总宽度的一半*/
         200px;
        height: 200px;
        background: blue;
    }        
</style>
复制代码

 浏览器效果图:

 

 是不是达到我们想要的结果了(认真看代码中的注释)。

原文地址:https://www.cnblogs.com/itjeff/p/14763342.html