一、文本
1、单行文本
代码:
<!DOCTYPE html>
<html>
<head>
<style>
div {
width: 200px;
height: 100px;
border: 1px solid black;
text-align: center;
background-color: greenyellow;
}
span {
line-height: 100px;
}
</style>
</head>
<body>
<div><span>单行文本</span></div>
</body>
</html>
显示结果:
2、多行文本
代码:
<!DOCTYPE html>
<html>
<head>
<style>
div {
width: 200px;
height: 100px;
border: 1px solid black;
text-align: center;
display: table;
background-color: greenyellow;
}
span {
display: table-cell;
vertical-align: middle;
}
</style>
</head>
<body>
<div><span>多行文本多行文本多行文本多行文本多行文本多行文本多行文本多行文本</span></div>
</body>
</html>
显示结果:
二、盒子
1、flex
代码:
<!DOCTYPE html>
<html>
<head>
<style>
.container {
width: 300px;
height: 300px;
border: 1px solid black;
background-color: greenyellow;
display: flex;
justify-content: center;
align-items: center;
}
.item {
width: 100px;
height: 100px;
background-color: red;
border: 1px solid black;
}
</style>
</head>
<body>
<div class="container">
<div class="item"></div>
</div>
</body>
</html>
显示结果:
2、position+margin
(1)第一种
适用于:已知当前div的width和height。
代码:
<!DOCTYPE html>
<html>
<head>
<style>
.container {
width: 300px;
height: 300px;
border: 1px solid black;
background-color: greenyellow;
position: relative;
}
.item {
width: 100px;
height: 100px;
background-color: red;
border: 1px solid black;
position: absolute;
top: 50%;
left: 50%;
margin-left: -50px;
margin-top: -50px;
}
</style>
</head>
<body>
<div class="container">
<div class="item"></div>
</div>
</body>
</html>
显示结果:
(2)第二种
代码:
<!DOCTYPE html>
<html>
<head>
<style>
.container {
width: 300px;
height: 300px;
border: 1px solid black;
background-color: greenyellow;
position: relative;
}
.item {
width: 100px;
height: 100px;
background-color: red;
border: 1px solid black;
position: absolute;
top: 0;
left: 0;
right: 0;
bottom: 0;
margin: auto;
}
</style>
</head>
<body>
<div class="container">
<div class="item"></div>
</div>
</body>
</html>
显示结果:
3、position+transform
代码:
<!DOCTYPE html>
<html>
<head>
<style>
.container {
width: 300px;
height: 300px;
border: 1px solid black;
background-color: greenyellow;
position: relative;
}
.item {
width: 100px;
height: 100px;
background-color: red;
border: 1px solid black;
position: absolute;
top: 50%;
left: 50%;
transform: translate(-50%,-50%)
/* 往左,往上移动自身长度的一半 */
}
</style>
</head>
<body>
<div class="container">
<div class="item"></div>
</div>
</body>
</html>
显示结果: