absolute,relative,left,right,bottom,top,float,z-index属性的讨论

来源:互联网 发布:赵云 知乎 编辑:程序博客网 时间:2024/05/12 06:09
<!DOCTYPE html PUBliC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"><html xmlns="http://www.w3.org/1999/xhtml"><head><title>absolute,relative,left,right,bottom,top,float,z-index属性的讨论</title><style type="text/css">body{margin:20px;font-family:Arial;font-size:12px;}#father{background-color:#a0c8ff;border:1px dashed #000000;padding:15px;position:relative;}#block1{%float:left;width:50%;position:relative;background-color:#fff0ac;border:1px dashed #000000;padding:10px;}#block2{position:absolute;background-color:#fff0ac;border:1px dashed #000000;width:100px;height:50px;%top:0px;%right:0px;}</style></head><body><div id="father">11111<div id="block2">Box-2</div></div></body></html>

考虑只有一个子div的情况:

当定位属性position设置成absolute之后,如果没有设置top,left,bottom,right中的某些属性

则子div的位置会根据父div中的内容来排列子div。如果都不设置,将zidiv定位在父div内容的左下方放置。

并不会放在父div内容之中,无论父div内容中是否能容纳子div。

<!DOCTYPE html PUBliC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"><html xmlns="http://www.w3.org/1999/xhtml"><head><title>absolute,relative,left,right,bottom,top,float,z-index属性的讨论</title><style type="text/css">body{margin:20px;font-family:Arial;font-size:12px;}#father{background-color:#a0c8ff;border:1px dashed #000000;padding:15px;position:relative;}#block1{%float:left;width:50%;position:relative;background-color:#fff0ac;border:1px dashed #000000;padding:10px;}#block2{position:absolute;background-color:#fff0ac;border:1px dashed #000000;width:100px;height:50px;%top:0px;%right:0px;}</style></head><body><div id="father"><div id="block1">Box-1</div><div id="block2">Box-2</div></div></body></html>
考虑两个子div,第一个子div设置为相对定位,第二个子div设置为绝对定位,在这里先将第一个div设置成float,同样没有设置top,left,bottom,right,你会发现如前面所说的第二个div定位在父div内容的左下方,并且与第一个子div重叠,这里第一个子div不再占用父div的内容空间。当将第一个div的float取消之后,第二个div也定位在父div内容的左下方,不与第一个子div重叠,这里第一个子div占用父div的内容空间。

由此可以看出来:

1、给块元素设置float之后,将脱离文档流,块元素的宽度会根据块元素的内容的大小变化,如果不设置float其宽度默认为浏览器宽度。
2、给块元素设置float之后,该块元素不再占用父级div的内容空间。

3、在设置position属性的时候应该设置好top,left,bottom,right,然后根据需要将这些设置好的属性取消达到特定的效果。

0 0
原创粉丝点击