子级相对级居中对齐的几种方式
程序员文章站
2022-04-26 16:04:51
...
一. 父元素相对定位, 子元素绝对定位,然后右下偏移top: 50%; left: 50%; 再反向偏移transform: transtlate(-50%, -50%), 如果知道子元素的宽高, 也可以直接把反向偏移写死
<style>
.absolute001{
position: relative;
}
.absolute001 .son{
position: absolute;
left: 50%;
top: 50%;
transform: translate(-50%, -50%);
}
</style>
<style>
.absolute002{
position: relative;
}
.absolute002 .son{
position: absolute;
top: 50%;
left: 50%;
transform: translate(-25px, -50px);
}
</style>
二: 与第一种类似,但比较hack, 父元素相对定位,子元素绝对定位,设置margin: auto
; 上下左右都为0
<style>
.absolute003{
position: relative;
}
.absolute003 .son{
position: absolute;
margin: auto;
left: 0;
right: 0;
top: 0;
bottom: 0;
}
</style>
三. 父元素使用flex布局, 横向居中, 纵向居中
<style>
.flex001{
display: flex;
justify-content: center;
align-items: center;
}
</style>
完整测试:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
<style>元素居中</style>
<style>
.father{
width: 500px;
height: 200px;
background-color: #ea6f5a;
border: 1px solid #d29922;
margin: 0 auto;
color: #fdf6e3;
}
.son{
width: 200px;
height: 100px;
background-color: #0c8ac5;
}
</style>
</head>
<body>
<div class="father absolute001">
<style>
.absolute001{
position: relative;
}
.absolute001 .son{
position: absolute;
left: 50%;
top: 50%;
transform: translate(-50%, -50%);
}
</style>
<div class="son">绝对定位: 无需知道子元素宽高</div>
</div>
<div class="father absolute002">
<style>
.absolute002{
position: relative;
}
.absolute002 .son{
position: absolute;
top: 50%;
left: 50%;
transform: translate(-100px, -50px);
}
</style>
<div class="son">绝对定位: 需要知道子元素宽高(比较low)</div>
</div>
<div class="father absolute003">
<style>
.absolute003{
position: relative;
}
.absolute003 .son{
position: absolute;
margin: auto;
left: 0;
right: 0;
top: 0;
bottom: 0;
}
</style>
<div class="son">绝对定位: 无需知道子元素宽高(hack玩法, 记得margin: auto)</div>
</div>
<div class="father flex001">
<style>
.flex001{
display: flex;
justify-content: center;
align-items: center;
}
</style>
<div class="son">flex定位:无需知道子元素宽高(好用, 推荐)</div>
</div>
</body>
</html>