2018-07-16
2018-07-16 本文已影响0人
阿狸菌不是细菌
1.定位
1.相对定位
相对定位就是元素在页面上正常的位置
相对定位一般不使用right,bottom
<style>
div{
width:100px;
height:100px;
background: red;
position: relative;
left:200px;
top:200px;
}
</style>
</head>
<body>
<!-- 定位 -->
<!--
相对定位
绝对定位
-->
<div>
</div>
</body>

2.绝对定位
绝对定位的元素移动的位置,是离它最近的给了定位的父元素
<style>
.parent{
width:200px;
height:200px;
background-color:red;
position: relative;
}
.child{
width:50px;height:50px;background:green;
position:absolute;
right:0;
bottom:0;
}
</style>
</head>
<body>
<div class="parent">
<div class="child">
</div>
</div>
</body>

3.元素垂直水平居中
<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>
</head>
<body>
<div class="parent">
<div class="child">
</div>
</div>
</body>

4.百分比赋值
<style>
*{margin:0;padding:0}
html,body{
width:100%;
height:100%;
}
/* 子元素left,top值给百分比,是相对于父元素的width,height而言的 */
img{
position:absolute;
left:50%;
top:50%;
width:618px;
height:128px;
margin-left:-307px;
margin-top: -64px;
}
body{
position: relative;
background:url("images/bg.png") no-repeat center center;
background-size: cover;
}
</style>
</head>
<body>
<img src="images/phone.png" alt="">
</body>

5.search
<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>
</head>
<body>
<div class="search">
<input type="text" placeholder="搜索">
<button></button>
</div>
</body>

6.fixed
<style>
div{
width:20px;
height:50px;
background:red;
position:fixed;
right:10px;
bottom:130px;
}
</style>
</head>
<body>
<div></div>
</body>
此图永远处于屏幕这个位置,不会随滚轮滚动而改变

7. z-index
z-index设置给了absolute定位元素的堆叠顺序
<style>
.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: 10;
}
</style>
</head>
<body>
<!-- z-index -->
<div class="parent">
<div class="one"></div>
<div class="two"></div>
</div>
</body>

<style>
.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;
}
</style>
</head>
<body>
<!-- z-index -->
<div class="parent">
<div class="one"></div>
<div class="two"></div>
</div>
</body>
