Javascript 5 - DOM
position: absolute;
An element with position: absolute; is positioned relative to the nearest positioned ancestor
position: relative;
An element with position: relative; is positioned relative to its normal position.
<div id="box1"><!--参照定位的元素-->
<div id="box2">相对参照元素进行定位</div><!--相对定位元素-->
</div>
#box1{
width:200px;
height:200px;
position:relative;
}
#box2{
position:absolute;
top:20px;
left:30px;
}
**已知宽高实现盒子水平垂直居中 **
<head>
<meta charset="UTF-8">
<title>已知宽高实现盒子水平垂直居中</title>
<style type="text/css">
.box {
border: 1px solid #00ee00;
height: 300px;
position: relative;
}
.box1 {
position: absolute;
top: 50%;
left: 50%;
margin: -100px 0px 0px -100px;
width: 200px;
height: 200px;
border: 1px solid red;
}
</style>
</head>
<body>
<div class="box">
<div class="box1"></div>
</div>
</body>
宽高不定实现盒子水平垂直居中
<head>
<meta charset="UTF-8">
<title>宽高不定实现盒子水平垂直居中</title>
<style type="text/css">
.box {
border: 1px solid #00ee00;
height: 300px;
position: relative;
}
.box1 {
border: 1px solid red;
position: absolute;
top: 50%;
left: 50%;
transform: translate(-50%, -50%);
}
</style>
</head>
<body>
<div class="box">
<div class="box1">
网网网网网网网网网网网网网网网网网网网网网网
</div>
</div>
</body>