要實現如圖一所示的結果:
html代碼如下:
<!DOCTYPE html>
<html><head lang="zh"><meta http-equiv="X-UA-Compatible" content="IE=edge"><meta charset="utf-8" /><title>商品管理后臺首頁</title><link rel="stylesheet" href="./css/index.css" />
</head><body><div class="content"><span>這是一個測試要居中</span><div class="box">我是div中的文字</div></div>
</body></html>
相應的less代碼
.content{width: 500px;height: 200px;border:1px solid red;position: relative;line-height: 200px;/*讓class=content父div中的文字垂直居中*/span{background: green;}.box{background: yellow;float: left;width: 200px;height: 100px;line-height: 100px;/*讓黃色div中的文字內容垂直居中*/text-align: center;/*讓文字水平居中*/position: absolute;top:50%;margin-top: -50px;margin-left: 200px; }
}
②使用vertical-align:middle設置在父元素中的位置,
效果圖:
html代碼:
<!DOCTYPE html>
<html>
<head lang="zh"><meta http-equiv="X-UA-Compatible" content="IE=edge"><meta charset="utf-8" /><title>商品管理后臺首頁</title><link rel="stylesheet" href="./css/index.css" />
</head><body><div class="content">我是div中的文字<div class="pox">我是子元素的文字</div></div>
</body>
</html>
相應的css代碼:
.content{width: 500px;height: 200px;line-height: 200px;/*設置其文字內容垂直居中*/border:1px solid red;.pox{background: yellow;width: 200px;height: 70px;display: inline-block; /*一定要將div設置為inline-block*/vertical-align: middle;/*設置該元素在父元素中的位置*/line-height: 70px;border: 1px solid green;text-align: center;}
}
化簡后的核心代碼:
.content{width: 500px;height: 200px;line-height: 200px;/*設置其文字內容垂直居中*/background:red;.pox{height: 70px;/*給內部div設置了高度,該div才會垂直居中*/display: inline-block; /*一定要將div設置為inline-block*/vertical-align: middle;/*設置該元素在父元素中的位置*/background: yellow;}
}