码迷,mamicode.com
首页 > 其他好文 > 详细

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

时间:2017-10-13 20:12:32      阅读:5691      评论:0      收藏:0      [点我收藏+]

标签:浏览器   指点   ati   body   宽度   oct   -o   images   水平   

声明: 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>

 

 浏览器效果图:

 技术分享

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

 

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

标签:浏览器   指点   ati   body   宽度   oct   -o   images   水平   

原文地址:http://www.cnblogs.com/taohuaya/p/7662635.html

(1)
(3)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!