zoukankan      html  css  js  c++  java
  • 绝对定位后,position:absolute;不能使用margin: 0 auto;实现居中;

    声明: web小白的笔记,欢迎大神指点!联系QQ:1522025433.

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

    请看实例:

    <!doctype html>
    <html>
    <head>
    <meta charset="utf-8">
    <title>绝对定位后margin: 0 auto;居中失效的解决方法</title>
    <style type="text/css">
        .test-out {
    
            width: 500px;
            height: 500px;
            margin: 0 auto; /*实现父元素居中*/
            background: red;
        }
        .test-in {
            width: 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; /*作为子元素的 定位包含框,使子元素在父元素内 进行定位*/
            width: 500px;
            height: 500px;
            margin: 0 auto; /*实现父元素居中*/
            background: red;
        }
        .test-in {
            position: absolute;  /*子元素实现绝对定位*/
            width: 200px;
            height: 200px;
            margin: 0 auto;/* 此时会失效*/
            background: blue;
        }

    浏览器效果:

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

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

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

    具体代码如下:

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

     浏览器效果图:

     

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

  • 相关阅读:
    反射 动态导入 元类
    面向对象的继承
    面向对象基础总结
    面向对象基础
    包 logging hashlib copy模块
    os random sys json 模块
    【1012 | Day 43】前端之CSS(下)
    【1011 | Day 42】灵魂拷问:数据放在服务端和客户端的利与弊?
    【1011 | Day 42】socket实现ftp文件的上传和下载
    【1011 | Day 42】前端之CSS(上)
  • 原文地址:https://www.cnblogs.com/taohuaya/p/7662635.html
Copyright © 2011-2022 走看看