绝对定位 不能通过 设置 margin: auto;
样式的方式 , 设置盒子模型水平居中 ;
相对定位 的 盒子模型 , 并没有脱离标准流限制 , 仍然可以使通过设置 margin: auto;
样式的方式 令盒子水平居中 ;
举例说明 : 绝对定位 的元素 需要居中对齐的地方很多 , 如下图所示 , 右侧的 固定定位 按钮 , 需要在浏览器中居中对齐 , 轮播图中的 五个小圆点 的容器需要居中对齐 ;
使 绝对定位 元素 水平 / 垂直 居中 最简单的方法就是 使用标尺测量父容器的宽高 , 通过设置四个边的边偏移量 , 设置元素 水平 / 垂直 居中 ;
父容器 盒子 如果尺寸发生了改变 , 使用上述固定边偏移的方式设置的居中就会出现问题 ;
先设置 50% 的 宽度 / 高度 偏移量 , 然后再往回退 盒子一半 宽度 / 高度 的偏移量 ;
以 水平居中为例 : 200 x 200 大小的盒子 , 通过设置
left: 50%;
margin-left: -100px;
为 80x80 像素尺寸的元素设置 水平 / 垂直 居中 ;
left: 50%;
, 再设置 margin-left: -40px
向左移动 40 像素 ; /* 绝对定位元素 - 水平居中 */
.top {
/* 子元素设置绝对定位 父元素需要设置相对定位 */
position: absolute;
/* 该盒子在父容器左上角 */
/* 上边偏移 0 紧贴顶部 */
top: 0;
/* 左边偏移 50% 左侧紧贴水平居中位置 */
left: 50%;
/* 再向做移动 40 像素, 水平居中 */
margin-left: -40px;
/* 内容尺寸 */
width: 80px;
height: 80px;
background-color: blue;
}
top: 50%;
, 然后再向上移动 40 像素 ; /* 绝对定位元素 - 垂直居中 */
.bottom {
/* 子元素设置绝对定位 父元素需要设置相对定位 */
position: absolute;
/* 该盒子在父容器右下角 */
/* 顶部移动到垂直中心位置 */
top: 50%;
/* 右边偏移 0 紧贴右侧 */
right: 0;
/* 垂直方向上 , 再向上走 40 像素 使得垂直居中 */
margin-top: -40px;
/* 内容尺寸 */
width: 80px;
height: 80px;
background-color: red;
}
代码示例 :
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>绝对定位示例</title>
<style>
/* 最外层 父容器盒子 */
.box {
/* 子元素设置绝对定位 父元素需要设置相对定位 */
position: relative;
/* 内容尺寸 通过测量图片获得 */
width: 300px;
height: 200px;
/* 边框 1 像素实线 */
border: 1px solid #ccc;
/* 上下设置 100 像素外边距 水平居中 */
margin: 100px auto;
/* 子元素与 */
padding: 10px;
background-color: pink;
}
/* 标准流元素 */
.center {
width: 300px;
height: 200px;
background-color: purple;
}
/* 绝对定位元素 - 水平居中 */
.top {
/* 子元素设置绝对定位 父元素需要设置相对定位 */
position: absolute;
/* 该盒子在父容器左上角 */
/* 上边偏移 0 紧贴顶部 */
top: 0;
/* 左边偏移 50% 左侧紧贴水平居中位置 */
left: 50%;
/* 再向做移动 40 像素, 水平居中 */
margin-left: -40px;
/* 内容尺寸 */
width: 80px;
height: 80px;
background-color: blue;
}
/* 绝对定位元素 - 垂直居中 */
.bottom {
/* 子元素设置绝对定位 父元素需要设置相对定位 */
position: absolute;
/* 该盒子在父容器右下角 */
/* 顶部移动到垂直中心位置 */
top: 50%;
/* 右边偏移 0 紧贴右侧 */
right: 0;
/* 垂直方向上 , 再向上走 40 像素 使得垂直居中 */
margin-top: -40px;
/* 内容尺寸 */
width: 80px;
height: 80px;
background-color: red;
}
</style>
</head>
<body>
<div class="box">
<div class="top"></div>
<div class="center"></div>
<div class="bottom"></div>
</div>
</body>
</html>
执行效果 :
扫码关注腾讯云开发者
领取腾讯云代金券
Copyright © 2013 - 2025 Tencent Cloud. All Rights Reserved. 腾讯云 版权所有
深圳市腾讯计算机系统有限公司 ICP备案/许可证号:粤B2-20090059 深公网安备号 44030502008569
腾讯云计算(北京)有限责任公司 京ICP证150476号 | 京ICP备11018762号 | 京公网安备号11010802020287
Copyright © 2013 - 2025 Tencent Cloud.
All Rights Reserved. 腾讯云 版权所有