绝对定位居中

绝对定位居中

  • 设置水平居中 先设置子元素左侧移动到水平中心位置 left: 50%; , 再设置 margin-left: -40px 向左移动 50% ;
/* 绝对定位元素 - 水平居中 */
.top {
/* 子元素设置绝对定位 父元素需要设置相对定位 */
position: absolute;
/* 该盒子在父容器左上角 */
/* 上边偏移 0 紧贴顶部 */
top: 0;
/* 左边偏移 50% 左侧紧贴水平居中位置 */
left: 50%;
/* 再向左移动元素自身的50%, 水平居中 */
margin-left: -50%;
/* 内容尺寸 */
width: 80px;
height: 80px;
background-color: blue;
}
  • 设置垂直居中 : 先设置子元素顶部移动到父容器垂直中心位置 top: 50%; , 然后再向上移动50% ;
/* 绝对定位元素 - 垂直居中 */
.bottom {
/* 子元素设置绝对定位 父元素需要设置相对定位 */
position: absolute;
/* 该盒子在父容器右下角 */
/* 顶部移动到垂直中心位置 */
top: 50%;
/* 右边偏移 0 紧贴右侧 */
right: 0;
/* 垂直方向上 , 再向上移动元素自身高度的50% 使得垂直居中 */
margin-top: -50%;
/* 内容尺寸 */
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%;
margin-left: -50%;
/* 内容尺寸 */
width: 80px;
height: 80px;
background-color: blue;
}
/* 绝对定位元素 - 垂直居中 */
.bottom {
/* 子元素设置绝对定位 父元素需要设置相对定位 */
position: absolute;
/* 该盒子在父容器右下角 */
/* 顶部移动到垂直中心位置 */
top: 50%;
/* 右边偏移 0 紧贴右侧 */
right: 0;
margin-top: -50%;
/* 内容尺寸 */
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>
posted @   Ewar-k  阅读(35)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· TypeScript + Deepseek 打造卜卦网站:技术与玄学的结合
· Manus的开源复刻OpenManus初探
· AI 智能体引爆开源社区「GitHub 热点速览」
· 三行代码完成国际化适配,妙~啊~
· .NET Core 中如何实现缓存的预热?
点击右上角即可分享
微信分享提示