验证码: 看不清楚,换一张 查询 注册会员,免验证
  • {{ basic.site_slogan }}
  • 打开微信扫一扫,
    您还可以在这里找到我们哟

    关注我们

css绝对定位如何实现

阅读:599 来源:乙速云 作者:代码code

css绝对定位如何实现

一.基本概念:

如果说相对定位没有脱离文档流,相对于对象本身进行偏移有点拖泥带水的话,那么绝对定位绝对是快刀斩乱麻,因为绝对定位可以使一个对象脱离正常的文档流,好像是漂浮在正常文档流的上空,并相对于包含此对象的元素进行定位,当然这个定位相对元素在不同的情况下也有所不同。

二.如何将一个元素设置为绝对定位:

为对象添加如下属性即可将对象设置为绝对定位:

position:absolute;

或者

position:fixed

三.定位参考对象:

可以使用top属性和left属性设置绝对定位对象的偏移量。
绝对定位虽然脱离了文档流,但是也需要有定位的参考对象,不过在不同的情况下参考对象也是不同。

1.如果没有设置top或者left属性值,那么相应方位的定位参考对象就是此对象的一级父元素,代码实例如下:





CSS的绝对定位-蚂蚁部落  

body
{
margin:20px;
}
#grandfather
{
width:330px;
height:300px;
background-color:#F90;
}
#father
{
width:200px;
height:200px;
background-color:green;
margin-left:50px;
}
#children
{
width:100px;
height:100px;
background-color:red;
float:right;
}
#inner
{
width:50px;
height:50px;
background-color:blue;
position:absolute;
top:10px;
}





 
  
 

以上代码中,由于inner元素采用绝对定位,并且没有设置left属性值,所以在水平方位的定位参考对象就是inner元素的一级父元素children。当然如果没有设置top属性值,那么垂直方位的定位参考对象也是children。
2.如果设置了left或者top属性值情况:
1).如果祖先元素中有采用定位的,那么此对象的相应方位的定位参考对象就是此祖先元素,如果祖先元素没有采用定位的,那么相应方位的上的定位参考对象就是浏览器客户区,代码实例如下:

实例一:





CSS的绝对定位-蚂蚁部落  

body
{
margin:20px;
}
#grandfather
{
width:330px;
height:300px;
background-color:#F90;
}
#father
{
width:200px;
height:200px;
background-color:green;
margin-left:50px;
position:relative;
}
#children
{
width:100px;
height:100px;
background-color:red;
float:right;
}
#inner
{
width:50px;
height:50px;
background-color:blue;
position:absolute;
left:10px;
top:10px;
}





 
  
 




以上代码,inner元素采用绝对定位,并且它的祖先元素father采用相对定位,那么它的定位参考对象就是father。

实例二:





CSS的绝对定位-蚂蚁部落  

body
{
margin:20px;
}
#grandfather
{
width:330px;
height:300px;
background-color:#F90;
}
#father
{
width:200px;
height:200px;
background-color:green;
margin-left:50px;
}
#children
{
width:100px;
height:100px;
background-color:red;
float:right;
}
#inner
{
width:50px;
height:50px;
background-color:blue;
position:absolute;
top:10px;
}





 
  
 




以上代码中,inner元素采用绝对定位,并且它的祖先元素没有采用定位的,那么垂直方位的定位参考对象就是窗口,由于没有设置left属性值,那么水平方位的定位参考对象就是它的一级父元素children。

四.绝对定位元素脱离文档流:
在开头已经提到过,绝对定位能够使元素脱离文档流,那么它周边文档流中的元素就能够占据此元素没有脱离文档流时的位置。
代码如下:





CSS的绝对定位-蚂蚁部落  

div
{
text-align:center;
line-height:100px;
}
.father
{
width:400px;
height:400px;
background-color:green;
margin:50px;
}
.first
{
width:100px;
height:100px;
background-color:red;
position:absolute;
}
.second
{
width:120px;
height:120px;
background-color:blue;
}




first
second


分享到:
*特别声明:以上内容来自于网络收集,著作权属原作者所有,如有侵权,请联系我们: hlamps#outlook.com (#换成@)。
相关文章
{{ v.title }}
{{ v.description||(cleanHtml(v.content)).substr(0,100)+'···' }}
你可能感兴趣
推荐阅读 更多>