一、文本居中
水平居中:text-align: center;
单行文本垂直居中
line-height: xxxpx;(父盒子行高 = 父盒子高度)
多行文本垂直居中
- 方法1,利用弹性布局flex+align-items
.box {
display: flex;
align-items: center;
width: 500px;
height: 500px;
background-color: yellow;
}
方法2,父line-height+子行内块+子line-height自定义设置
先对父元素设置高度和行高(相等),将子元素设置为行内块元素,模拟成单行文本,再对子元素设置vertical-align: middle;使其基线对齐,这时还未实现垂直居中,为子元素自定义line-height属性的值,覆盖继承自父元素的行高,即可实现垂直居中。
.box {
width: 500px;
height: 500px;
line-height: 500px;
background-color: yellow;
}
span {
display: inline-block;
vertical-align: middle;
line-height: 18px;
}
方法3,子元素设为行内块元素+利用相对定位进行平移(translateY)
.text {
width: 500px;
height: 500px;
background-color: yellow;
}
span {
display: inline-block;
position: relative;
top: 50%;
transform: translateY(-50%);
}
方法4,利用表格元素table+vertical-align实现
.text {
display: table;
width: 500px;
height: 500px;
background-color: yellow;
}
span {
display: table-cell;
vertical-align: middle;
}
二、图片居中
方法1:
水平居中,给父元素设 text-align: center;
垂直居中,给父元素设 line-height: xxxpx 的同时给图片设 vertical-align: middle;方法2:
给父元素设 background: url(./upload/floor-1-1.png) no-repeat center 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">
<link rel="stylesheet" href="css/base.css">
<title>Document</title>
<style>
* {
margin: 0;
padding: 0;
box-sizing: border-box;
}
.reg_form {
width: 600px;
height: 400px;
/* background-color: pink; */
border: 1px solid #ccc;
margin: 50px auto 0;
}
.reg_form ul li {
border: 1px solid #ccc;
}
.reg_form ul li label {
display: inline-block;
width: 88px;
text-align: right;
}
.reg_form ul li input {
width: 242px;
height: 37px;
border: 1px solid #ccc;
}
.error {
color: #c81523;
}
.error_icon {
display: inline-block;
width: 20px;
height: 20px;
background: url(./images/error.png) no-repeat;
vertical-align: middle;
}
.str{
vertical-align: middle;
}
</style>
</head>
<body>
<div class="reg_form">
<ul>
<li>
<label for="">手机号:</label>
<input type="text">
<span class="error"><i class="error_icon"></i> <strong class="str">手机号码格式不正确,请重新输入</strong></span>
</li>
</ul>
</div>
</body>
</html>