一、写在前面
今天看到一个面试题,问未知大小的父元素如何实现让其子元素水平垂直居中。现在总结一下几种方法。
二、实现方法2.1、flex布局
<!DOCTYPE html>
<html lang="cn">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
<style>
.parent {
width: 200px;
height: 200px;
background-color: red;
display:flex;
justify-content: center;
align-items: center;
}
</style>
</head>
<body>
<div class="parent">
<div class="child">hello world</div>
</div>
</body>
</html>
2.2、使用table布局
<!DOCTYPE html>
<html lang="cn">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
<style>
.parent {
width: 200px;
height: 200px;
display: table;
background-color: red;
}
.child {
display: table-cell;
vertical-align: middle;
text-align: center;
}
</style>
</head>
<body>
<div class="parent">
<div class="child">hello world</div>
</div>
</body>
</html>
2.3、transform
<!DOCTYPE html>
<html lang="cn">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
<style>
.parent {
width: 200px;
height: 200px;
background-color: red;
position: relative;
}
.child {
position: absolute;
left: 50%;
top: 50%;
transform: translate(-50%, -50%);
}
</style>
</head>
<body>
<div class="parent">
<div class="child">hello world</div>
</div>
</body>
</html>
2.4、
版权说明 : 本文为转载文章, 版权归原作者所有 版权申明
原文链接 : https://blog.csdn.net/weixin_47450807/article/details/123666444
内容来源于网络,如有侵权,请联系作者删除!