css 水平居中整理
程序员文章站
2022-05-11 08:16:42
...
1.利用table属性 父元素设为display:table;子元素设为display:table-cell;vertical-align:middle;text-align:center; 具体代码为
.parent {
width:300px;
height:300px;
background:#000;
display:table;
}
.child {
display:table-cell;
color:#fff;
vertical-align:middle;
text-align:center;
}
<div class = "parent">
<div class="child">hello</div>
</div>
2.利用css3的特性 transform:translate(-50%,-50%),具体代码如下:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>未知宽高元素水平垂直居中</title>
</head>
<style>
.parent {
width: 500px;
height: 500px;
background: #ff0;
position: relative;
}
.child {
margin-left: 50%;
margin-top:50%;
position: absolute;
transform: translate(-50%,-50%);
}
</style>
<body>
<div class="parent">
<div class="child">hello world-2</div>
</div>
</body>
</html>
3,利用flex布局。主要是父元素设置display:flex,justify-content:center;align-item:center;代码如下:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>未知宽高元素水平垂直居中</title>
</head>
<style>
.parent {
display: flex;
justify-content: center;
align-items: center;
width: 300px;
height: 300px;
background: #f0f;
}
</style>
<body>
<div class="parent">
<div class="child">hello world-2</div>
</div>
</body>
</html>
上一篇: 纯css3圆形从中心向四周扩散动画效果
下一篇: 通过案例学调优之--OracleADDM