<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>水平垂直居中</title>
<style>
/*1. flex布局, 只需对父元素操作 */
/* .parent {
display: flex;
align-items: center;
justify-content: center;
} */
/*2. 绝对定位, 利用 top,left 向右下移动一半父元素的距离,然后用 transform 左上移动自身元素的一半距离 */
/* .parent {
position: relative;
}
.content {
position: absolute;
top: 50%;
left: 50%;
transform: translate(-50%, -50%);
} */
/*3. 绝对定位, 把上述的 transform 换成 负margin 自身宽高的一半。此方案需要已知宽高。*/
/* .parent {
position: relative;
}
.content {
position: absolute;
86px;
height: 21px;
top: 50%;
left: 50%;
margin-left: -43px;
margin-top: -10.5px;
} */
/*4. 绝对定位, top,bottom,left,right 全部设置为0, margin: auto; 此方案需要已知宽高。*/
/* .parent {
position: relative;
}
.content {
position: absolute;
86px;
height: 21px;
left: 0;
right: 0;
top: 0;
bottom: 0;
margin: auto;
} */
/* 其他水平居中的办法主要有两个 */
/*1. 父元素 text-align: center; */
.parent {
text-align: center;
}
/*2. 子元素 margin: 0 auto; 此方案需要已知宽度。且只对block元素生效。*/
/* .content {
display: block;
86px;
margin: 0 auto;
} */
/* 其他垂直居中的办法主要有两个 */
/*1. 子元素设置 line-height 等于父元素高度 */
/* .content {
line-height: 500px;
} */
/*2. table布局,子元素: vertical-align: middle; */
.parent {
display: table;
}
.content {
display: table-cell;
vertical-align: middle;
}
</style>
</head>
<body>
<div class="parent" style=" height: 500px; 400px;background: gray;">
<div class="content" id="div" style="background: greenyellow;display:none;">hello world</div>
<span class="content" id="span" style="background: greenyellow;">hello world</span>
</div>
<button id="btn" style="margin-top:20px;margin-bottom: 40px;">切换span or div</button>
<div>参考文章:<a target="_blank" href="http://louiszhai.github.io/2016/03/12/css-center/">http://louiszhai.github.io/2016/03/12/css-center/</a></div>
<script>
var div = document.getElementById("div");
var span = document.getElementById("span");
var display = span.style.display;
document.getElementById('btn').onclick = function () {
if (div.style.display === "none") {
span.style.display = 'none';
div.style.display = display;
} else {
div.style.display = 'none';
span.style.display = display;
}
}
</script>
</body>
</html>