首页 > 开发 > CSS > 正文

css常用元素水平垂直居中方案

2024-07-11 08:38:10
字体:
来源:转载
供稿:网友

flex实现水平垂直居中

适用场景:父子宽高都可未知(比较推荐这种方式,简单,而且目前兼容性也不错。)


<html>
<head>
<style>
.parent {
width: 100%;
height: 100px;
background: cyan;
display: flex;
justify-content: center;
align-items: center;
}
.son {
width: 20%;
height: 20%;
background: pink;
}
</style>
</head>
<body>
<div class='parent'>
<div class='son'></div>
</div>
</body>
</html>

绝对定位加上负margin

适用场景:父元素宽高已知未知都行,但是首先得有宽高。其次子元素的宽高必须已知,因为需要设置子元素的负margin. (也可以将负margin设置成translate来做位移实现)


<html>
<head>
<style>
.parent {
position: relative;
width: 200px;
height: 200px;
background: pink;
}
.son {
position: absolute;
left: 50%;
top: 50%;
margin-left: -25px;
margin-top: -25px;
width: 50px;
height: 50px;
background: yellow;
}
</style>
</head>
<body>
<div class='parent'>
<div class='son'></div>
</div>
</body>
</html>

绝对定位 + auto margin

适用场景:父子元素宽高都未知的情况(该方式不需要明确知道子元素宽高,子元素宽高可用百分比,对于子元素宽高不确定需要居中的情况比较适合。)


<html>
<head>
<style>
.parent {
position: relative;
width: 200px;
height: 200px;
background: cyan;
}
.son {
position: absolute;
left: 0;
top: 0;
bottom: 0;
right: 0;
margin: auto;
width: 10%;
height: 10%;
background: yellow;
}
</style>
</head>
<body>
<div class='parent'>
<div class='son'></div>
</div>
</body>
</html>

网格布局

适用场景:父子元素宽高未知,兼容性不大好


<html>
<head>
<style>
.parent {
display: grid;
}
.son {
jusitify-self: center;
align-self: center;
}
</style>
</head>
<body>
<div class='parent'>
<div class='son'></div>
</div>
</body>
</html>

Table-cell + text-align + vertical-align

适用场景: 父元素大小已知(非百分比高度),子元素大小未知,但子元素须为行内块元素,较好的兼容性

            
发表评论 共有条评论
用户名: 密码:
验证码: 匿名发表