掌握盒子水平垂直居中方案
两个盒子,大盒子和小盒子,实现小盒子在大盒子内部水平垂直居中。
定位三种
定位方法一(明确盒子高和宽的值)
```html
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>定位</title>
<style type="text/css">
/* 注意css高度继承 */
html,body{
height: 100%;
overflow: hidden;
}
.box{
box-sizing: border-box;
height: 50px;
width: 100px;
line-height: 48px;
text-align: center;
border: 1px brown solid;
}
body{
position: relative;
}
.box{
position: absolute;
/* 让盒子的左上角在整个页面实现水平垂直居中 */
top: 50%;
left: 50%;
/* 将盒子往上移高一半往左移宽一半 */
margin-top: -25px;
margin-left: -50px;
}
</style>
</head>
<body>
<!-- 以前常用方法(注意需要明确box的高和宽) -->
<div class="box">
居中
</div>
</body>
</html>
定位方法二(不需要明确盒子高和宽的值,但需要存在高和宽)
**定位方法二**
```css
.box{
position: absolute;
top: 0;
bottom: 0;
left: 0;
right: 0;
margin: auto;
}
定位方法三利用CSS3的transform特性
(不需要盒子高和宽,但无法兼容)
.box{
position: absolute;
top: 50%;
left: 50%;
/* 以自己宽度向左向下移动50% */
transform: translate(-50%,-50%);
}
display:flex(注意:不兼容,移动端常用)
body{
display: flex;
align-items: center;
justify-content: center;
}
JavaScript方式(js方式动态设置)
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>水平垂直居中</title>
<style type="text/css">
/* 注意css高度继承 */
html,body{
height: 100%;
overflow: hidden;
}
.box{
box-sizing: border-box;
height: 50px;
width: 100px;
line-height: 48px;
text-align: center;
border: 1px brown solid;
}
body{
position: relative;
}
</style>
</head>
<body>
<div class="box">
居中
</div>
<script type="text/javascript">
let html = document.documentElement,
winW = html.clientWidth,
winH = html.clientHeight,
boxH = box.offsetHeight,
boxW = box.offsetWidth;
box.style.position = "absolute";
box.style.top = (winH - boxH)/2 + 'px';
box.style.left = (winW - boxW)/2 + 'px';
</script>
</body>
</html>
display:table-cell(本身控制文本,若要用要求父级要有固定宽高)
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>水平垂直居中</title>
<style type="text/css">
/* 注意css高度继承 */
html,body{
/* height: 100%; */
overflow: hidden;
}
.box{
box-sizing: border-box;
height: 50px;
width: 100px;
line-height: 48px;
text-align: center;
border: 1px brown solid;
}
body{
display: table-cell;
vertical-align: middle;
text-align: center;
width: 500px;
height: 500px;
border: #A52A2A 2px solid;
}
.box{
display: inline-block;
}
</style>
</head>
<body>
<div class="box">
居中
</div>
</body>
</html>