1. Texto
1. Texto de una sola línea
Código:
<!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>
Mostrar resultados:
2. Texto de varias líneas
Código:
<!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>
Mostrar resultados:
Segundo, la caja
1 、 flexible
Código:
<!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>
Mostrar resultados:
2 、 posición + margen
(1) El primero
Aplicar a: conoce el ancho y el alto del div actual.
Código:
<!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>
Mostrar resultados:
(2) El segundo
Código:
<!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>
Mostrar resultados:
3 、 posición + transformación
Código:
<!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>
Mostrar resultados: