通过几段案例代码,让您了解CSS的绝对定位、相对定位、fixed和static几种方法
以下讨论的是和定位 绝对定位 相对定位 fixed static相关的css基础教程之定位方法:绝对定位、相对定位、fixed和static 教程文章,内容是本站精心挑选整理的教程,希望对广大的网友给到帮助,下面是详细内容:
1.绝对定位(absolute):脱离原来位置进行定位,可以使用left right top bottom进行定位
html代码
hhhh
css代码:
*{ margin:0; padding:0; } .demo{ position:absolute; /*top:100px; left:100px;*/ width: 100px; height: 100px; background-color: red; opacity: 0.5; /*透明度*/ } .box{ width:150px; height:150px; background-color: green; }
2.相对定位(relative):保留原来位置进行定位,可以使用left right top bottom进行定位
html代码:
hhhh
css代码
*{ margin:0; padding:0; } .demo{ position:relative; /*top:100px; left:100px;*/ width: 100px; height: 100px; background-color: red; opacity: 0.5; /*透明度*/ } .box{ width:150px; height:150px; background-color: green; }
3.fixed:相对于浏览器的窗口对元素进行定位,可以使用left right top bottom进行定位
4.static:默认值,没有定位,top left 等不起作用
注意:存在父子元素使用定位时
absolute: 相对于最近的有定位的父级进行定位,要是没有最就相对文档进行定位
relative:相对于自己原来的位置进行定位
通常情况下,我们使用relative作为参照物,使用absolute进行定位
例如:
若使box参照demo进行定位则
*{ margin:0; padding:0; } .wrapper{ margin-left: 100px; width: 200px; height: 200px; background-color: orange; } .demo{ position:relative; margin-left: 100px; width: 100px; height: 100px; background-color: red; } .box{ position:absolute; left: 50px; width:50px; height:50px; background-color: green; }
关于css基础教程之定位方法:绝对定位、相对定位、fixed和static的内容写到这里就结束啦,您可以收藏本页网址http://www.alixixi.com/web/
a/2018091495987.shtml方便下次再访问哦。