css水平居中,竖直居中技巧(一)

时间:2022-08-07 14:49:28
css水平居中,竖直居中技巧(一)
===
### 1.效果

css水平居中,竖直居中技巧(一)


### 2.代码
#### 2.1.index.html
<!DOCTYPE html>
<html lang="zh-cn">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8"/>
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=no"/>
<meta name="renderer" content="webkit">
<title></title> <link rel="stylesheet/less" type="text/css" href="test.less"/>
<script type="text/javascript" charset="utf-8"
src="http://lib.jxt189.com/otherlib/less/2.6.1/dist/less.min.js"></script>
</head>
<body>
<h2>原始的效果</h2>
<div class="container">
<div class="inner-container">
<div>aaa</div>
<div>bbbbbb</div>
<div>ccccccccc</div>
</div>
</div>
<hr>
<h2>居中后的效果</h2>
<div class="container container-01">
<div class="inner-container container-02">
<div>aaa</div>
<div>bbbbbb</div>
<div>ccccccccc</div>
</div>
</div>
</body>
</html>
#### 2.2.test.less
.container {
width: 500px;
height: 300px;
background: red;
} .inner-container {
background: yellow;
} //核心代码
.container-01 {
position: relative; .container-02 {
@width: 150px;
@height: 100px; width: @width;
height: @height; position: absolute;
top: 50%;
left: 50%;
margin-top: -1*(@height / 2);
margin-left: -1*(@width / 2);
}
}
###3.说明
a.使用这种方式实现水平居中和垂直居中,需要对`.container-02`的容器设置宽度和高度