CSS中的定位布局position
定位时,通常使用left,top,right,bottom4个属性来进行定义
一、静态定位 static
left,top,right,bottom设置时将不起作用,要使用margin-left,margin-top,margin-right,margin-bottom
html代码如下:
<div class="one">one</div>
css代码如下:
.one{
width: 100px;
height: 100px;
background-color: pink;
/*“one”这个div粉色块与网页的左边相距10个像素*/
position: static;
margin-left: 10px;
}
二、相对定位 relation
1、不脱离文档流
2、根据本身位置进行定位
CSS代码如下:
.one{
width: 100px;
height: 100px;
background-color: pink;
/*one”这个div粉色块 与 网页的左边、上边各相距20个像素*/
position: relative;
left: 20px;
top: 20px;
}
三、固定定位 fixed:固定位置,不随窗口滚动而滚动
1、完全脱离文档流,不占据屏幕空间
2、根据浏览器进行定位
html代码如下:
<div class="one">one</div>
/*此处为了测试网页滚动之后仍固定在原位置,写多个br标签产生滚动条,可以使用"br*n"来快速编写*/
<br>
<br>
<br>
<br>
<br>
<br>
<br>
<br>
<br>
<br>
<br>
CSS代码如下:
.one{
width: 100px;
height: 100px;
background-color: pink;
/*one这个div粉色块固定在网页的右下角*/
position: fixed;
right: 0px;
bottom: 0px;
}
四、绝对定位 absolute
1、脱离文档流,不占据屏幕空间
2、若父元素无定位属性,那么根据浏览器进行定位
若父元素有定位属性,那么根据父元素左上角进行定位
html代码:
<div class="outer">
<div class="inner"></div>
</div>
第一种情况:父元素无定位属性
css代码:
.outer{
width: 400px;
height: 400px;
background-color: pink;
margin: 0 auto;
}
.inner{
width: 100px;
height: 100px;
background-color: coral;
position: absolute;
bottom: 0px;
right: 0px;
}
第二种情况:父元素有定位属性
css代码:
.outer{
width: 400px;
height: 400px;
background-color: pink;
margin: 0 auto;
position: relative;
}
.inner{
width: 100px;
height: 100px;
background-color: coral;
position: absolute;
bottom: 0px;
right: 0px;
}
以上就是css中定位布局的相关介绍,有更好的说明欢迎留言!