未知元素宽高居中的问题几乎是必问的题目!!!在个人经历的面试过程中,没家公司都问了,而且几乎是上来问的第一个问题。
第一种方法:定位
核心思路:定位(position:absolute)+位移(transform:translate)
<!DOCTYPE html>
<html lang="en">
<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>
* {
padding: 0;
margin: 0;
}
html,
body {
width: 100%;
height: 100%;
}
body {
background-color: azure;
}
.parent {
width: 100%;
height: 100%;
background-color: orangered;
text-align: center;
}cookie
.child {cookie
position: absolute;
top: 50%;
left: 50%;
transform: translate(-50%, -50%);
/* 使用css3的transform来实现 */
}
.child p {
width: 300px;
height: 400px;
background-color: blue;
}
</style>
</head>
<body>
<div class="parent">
<div class="child">
<p></p>
</div>
</div>
</body>
</html>
第二种方法:flex布局
flex布局,核心思想父元素:display:flex; justify-content:center;align-items:center;
<!DOCTYPE html>
<html lang="en">
<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>
*{
padding: 0;
margin: 0;
}
body,html{
width: 100%;
height: 100%;
}
.parent{
display: flex;
justify-content: center;
align-items: center;
width: 100%;
height:100%;
background: #FD0C70;
}
.parent .child{
color:#fff;
width: 200px;
height: 300px;
text-align: center;
background-color: yellow;
}
</style>
</head>
<body>
<div class="parent">
<div class="child">hello world</div>
</div>
</body>
</html>
第三种方法:table布局
display:table-cell;会使元素表现的类似一个表格中的单元格<td>。利用此特性实现水平垂直居中
<!DOCTYPE html>
<html lang="en">
<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{
display:table;
width:400px;
height:400px;
background:#666;
}
.children{
display:table-cell;
vertical-align:middle;
text-align:center;
background:red;
}
</style>
</head>
<body>
<div class="parent">
<div class="children"></div>
</div>
</body>
</html>