一.CSS中的定位
1.1相對(duì)定位(relative)
相對(duì)定位就是元素在頁面上正常的位置
<style>
/* 相對(duì)定位就是元素在頁面上正常的位置 */
div{
width:100px;
height:100px;
background: red;
position: relative;
left:200px;
top:200px;
/* 相對(duì)定位一般不使用right,bottom */
/* right:0px; */
/* bottom:10px; */
}
</style>
1.2絕對(duì)定位
絕對(duì)定位的元素移動(dòng)的位置,是離它最近的給了定位的父元素
<style>
.parent{
width:200px;
height:200px;
background-color:red;
position: relative;
}
/* 絕對(duì)定位的元素移動(dòng)的位置,是離它最近的給了定位的父元素 */
/* left,right,top,bottom */
.child{
width:50px;height:50px;background:green;
position:absolute;
right:0;
bottom:0;
}
</style>
<div class="parent">
<div class="child">
</div>
</div>
二.元素垂直水平居中
子元素left,top的值給百分比是相對(duì)于父元素的width,height而言的
步驟:①先設(shè)置父元素為相對(duì)定位
②設(shè)置子元素為絕對(duì)定位
<style>
*{margin:0;padding:0}
.parent{
position: relative;
width:300px;
height:300px;
background:red;
}
.child{
position:absolute;
width:50px;
height:50px;
background:green;
left:50%;
top:50%;
margin-left:-25px;
margin-top: -25px;
}
</style>
<body>
<div class="parent">
<div class="child">
</div>
</div>
</body>
三.用position實(shí)現(xiàn)搜索框
步驟:①先設(shè)置父元素search為相對(duì)定位良风,設(shè)置寬高
②設(shè)置子元素button為絕對(duì)定位,設(shè)置寬高谊迄,根據(jù)高來設(shè)置margin-top,使其高度居中
<style>
*{margin:0;padding:0}
.search{
margin:100px;width:240px;
height:40px;position: relative;
}
button{
position:absolute;top:50%;margin-top: -11px;
right:5px;width:23px;height:22px;
background: url("images/icon4.png");border:none;
}
input{
padding-left:20px;border:none;
border-radius: 30px;outline: none;
width:220px;height:40px;background:#eee;
}
</style>
<body>
<div class="search">
<input type="text" placeholder="搜索">
<button></button>
</div>
</body>
四.固定定位
元素相對(duì)于網(wǎng)頁靜止烟央,滾動(dòng)不改變位置
<style>
div{
width:20px;
height:50px;
background:red;
position:fixed;
right:10px;
bottom:130px;
}
</style>
五.z-index
z-index設(shè)置給了absolute定位元素的堆疊順序,設(shè)置值不小于100统诺,值越大,就堆疊在最前面
<style>
/* z-index設(shè)置給了absolute定位元素的堆疊順序 */
.parent{
width:300px;height:300px;background: red;
position: relative;
}
.one{
width:100px;
height:100px;
background:green;
position:absolute;
z-index:100;
}
.two{
width:200px;
height:50px;position:absolute;
background:blue;
z-index: 101;
}
.parent:hover .one{
z-index: 200;
}
<body>
<!-- z-index -->
<div class="parent">
<div class="one"></div>
<div class="two"></div>
</div>
</body>