(前端手撕)1.未知宽高元素垂直水平都居中
未知宽高元素垂直水平都居中
1. flex法
<!DOCTYPE html>
<html lang="en">
<head>
<style>
.wrap {
width: 200px;
height: 200px;
border: solid 1px red;
display: flex;
justify-content: center;
align-items: center;
}
.inner {
width: 80px;
height: 80px;
border: solid 1px blue;
}
</style>
</head>
<body>
<div class="wrap">
<div class="inner"></div>
</div>
</body>
</html>
————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————
2. 定位+transform
<!DOCTYPE html>
<html lang="en">
<head>
<style>
.wrap {
width: 200px;
height: 200px;
border: solid 1px red;
position: relative;
}
.inner {
width: 80px;
height: 80px;
border: solid 1px blue;
position: absolute;
left: 50%;
top: 50%;
transform: translate(-50%,-50%);
}
</style>
</head>
<body>
<div class="wrap">
<div class="inner"></div>
</div>
</body>
</html>
————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————
3. 表格
<!DOCTYPE html>
<html lang="en">
<head>
<style>
.wrap {
width: 200px;
height: 200px;
border: solid 1px red;
display: table-cell;
text-align: center;
vertical-align: middle;
}
.inner {
width: 80px;
height: 60px;
border: solid 1px blue;
display: inline-block;
}
</style>
</head>
<body>
<div class="wrap">
<div class="inner"></div>
</div>
</body>
</html>
————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————
4. 定位+auto
<!DOCTYPE html>
<html lang="en">
<head>
<style>
.wrap{
width: 200px;
height: 200px;
border: solid 1px red;
position: relative;
}
.inner {
width: 80px;
height: 80px;
border: solid 1px blue;
position: absolute;
left: 0;
top: 0;
right: 0;
bottom: 0;
margin: auto;
}
</style>
</head>
<body>
<div class="wrap">
<div class="inner"></div>
</div>
</body>
</html>
————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————
5. 网格
<!DOCTYPE html>
<html lang="en">
<head>
<style>
.wrap {
width: 200px;
height: 200px;
border: solid 1px red;
display: grid;
justify-content: center;
align-items: center;
}
.inner {
width: 80px;
height: 80px;
border: solid 1px blue;
}
</style>
</head>
<body>
<div class="wrap">
<div class="inner"></div>
</div>
</body>
</html>

