1.相对定位
<title>相对定位</title>
<style>
div {
width: 100px;
height: 100px;
margin: auto;
}
.a {
background-color: red;
}
.b {
background-color: gray;
/* position属性定义定位,默认值是static(静态定位) 表示不定位
此时left,right,top,bottom属性失效
position: relative;是相对定位,是相当于自己的位置重新定位,但是原来位置不会丢失*/
position: relative;
left: 50px;
top: 50px;
}
.c {
background-color: blue;
}
</style>
</head>
<body>
<div class="a"></div>
<div class="b"></div>
<div class="c"></div>
</body>
2.绝对定位
<title>绝对定位2</title>
<style>
* {
list-style: none;
padding: 0;
margin: 0;
}
/*,绝对定位是相对于离他最近定位父元素重新定位
如果没有定位父元素就相对于浏览器的左上角重新定位 ,绝对定位后的元素位置会丢失 */
.d {
width: 100px;
height: 100px;
background-color: red;
position: absolute;
left: 20px;
top: 20px;
}
.c {
width: 200px;
height: 200px;
border: 5px solid blue;
padding: 20px;
position: relative;
}
.b {
width: 300px;
height: 300px;
border: 5px solid green;
padding: 20px;
}
.a {
width: 400px;
height: 400px;
border: 5px solid orange;
padding: 20px;
margin: 10px auto;
}
</style>
</head>
<body>
<div class="a">
<div class="b">
<div class="c">
<div class="d"></div>
</div>
</div>
</div>
</body>
3.固定定位
<title>固定定位</title>
<style>
* {
list-style: none;
padding: 0;
margin: 0;
}
.a {
width: 200px;
height: 2000px;
background-color: pink;
}
.b {
width: 2000px;
height: 100px;
background-color: lightblue;
/* position: fixed;固定定位 将某个区域固定在位置,例如最顶端 */
position: fixed;
right: 20px;
top: 0px;
}
</style>
</head>
<body>
<div class="a"></div>
<div class="b"></div>
</body>
4.z-index
<title>z-index</title>
<style>
* {
list-style: none;
margin: 0;
padding: 0;
}
div {
width: 150px;
height: 150px;
position: absolute;
}
.a {
background-color: red;
z-index: 2;
}
.b {
background-color: blue;
left: 20px;
top: 20px;
/* z-index属性用于定位元素位置重叠时的调整顺序,默认值是0 */
/* 该值越大越靠上 */
z-index: 1;
}
.c {
background-color: brown;
left: 40px;
top: 40px;
}
</style>
</head>
<body>
<div class="a"></div>
<div class="b"></div>
<div class="c"></div>
</body>
5.盒子水平垂直居中
<title>盒子水平和垂直方向居中</title>
<style>
.box {
width: 600px;
height: 600px;
border: 1px black solid;
/* 父元素设置相对定位 */
position: relative;
}
.a {
width: 150px;
height: 150px;
background-color: red;
/* 子标签绝对定位,同时上下左右都为0,margin为auto */
position: absolute;
left: 0;
top: 0;
right: 0;
bottom: 0;
margin: auto;
}
</style>
</head>
<body>
<div class="box">
<div class="a"></div>
</div>
</body>
6.透明度
<title>透明度</title>
<style>
.box {
width: 200px;
height: 200px;
border: 1px red solid;
position: relative;
}
.box div {
width: 200px;
height: 200px;
}
.a {
text-align: center;
line-height: 200px;
font-size: 30px;
}
.b {
/* RGB中最后一个值是定义透明度 值的范围0-1 */
background-color: rgb(255, 0, 0, 0);
position: absolute;
left: 0;
top: 0;
/* opacity 透明度 属性值0是全透明 ,1是不透明 */
/* opacity: 0.5; */
}
</style>
</head>
<body>
<div class="box">
<div class="a">Helloworld</div>
<div class="b"></div>
</div>
</body>