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

时间:2023-12-04 13:23:14

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

浏览器效果图:

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

我们可以看出在正常情况下: 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;
}

浏览器效果:

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

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

绝对定位以后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:;
left: 50%; /*先定位到父元素(红盒)的中线,然后使子元素(红盒)的外边界 左偏移, 半个子元素(红盒) 的宽度,即可*/
margin-left: -100px;/*向左 偏移元素的总宽度的一半*/
width: 200px;
height: 200px;
background: blue;
}
</style>

浏览器效果图:

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

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