background属性和position属性

最近看到一个页面,当文本内容长时,背景不动,内容跟着变化,使用到了CSS的background-attachment:fixed属性,这篇文章,就来说一下background和position属性

1.CSS中的背景(背景是不可继承的)

  • background-color   默认值为transparent
  • background-image  参数设置如:url(./img.jpg)
  • background-repeat: repeat-y;  参数设置如:repeat-x  repeat-y  no-repeat
  • background-position:center;  参数设置如:top  bottom left right center,也可以使用百分号(指的是图像中心和元素中心对齐,如果设置为50% 50% 则在图像的最中间 如果设置为0 0 则在左上角对齐; 如果设置为100% 100%则为图像的右下角对齐。如果固定值则不同,设置值为 50px 100px,图像的左上角将在元素内边距区左上角向右 50 像素、向下 100 像素的位置上)
  • background-attachment:fixed;默认值是 scroll,参数为scroll  fixed。
  • background :  background-color background-position background-size background-repeat background-origin background-clip background-attachment  background-image  简写属性,参数设置

2.CSS的position属性

static:无特殊定位,对象遵循正常文档流。top,right,bottom,left ,z-index等属性不会被应用。


relative:对象遵循正常文档流,但将依据top,right,bottom,left等属性在正常文档流中偏移位置。而其层叠通过z-index属性定义。


absolute:对象脱离正常文档流,使用top,right,bottom,left等属性进行绝对定位。而其层叠通过z-index属性定义。( 如果使用absoulte或fixed定位的话,必须指定 left、right、 top、 bottom 属性中的至少一个,否则left/right/top/bottom属性会使用它们的默认值 auto ,这将导致对象遵从正常的HTML布局规则,在前一个对象之后立即被呈递,简单讲就是都变成relative,会占用文档空间,加上这两个属性是完全必要的.

除此之外,absoulte是根据祖先类的border进行的定位 ,<html>和<body>元素相差9px左右 relative和static方式在最外层时是以<body>标签为定位原点的,而absoulte方式在无父级是position非static定位时是以<html>作为原点定位。)


fixed:对象脱离正常文档流,使用top,right,bottom,left等属性以窗口为参考点进行定位,当出现滚动条时,对象不会随着滚动。而其层叠通过z-index属性定义。

参考一题小题:

链接:https://www.nowcoder.com/questionTerminal/33c230727abe4ed3972564fe6c9fef2a
来源:牛客网

以下代码,分别给节点
#box增加如下样式,问节点#box距离body的上边距是多少?

<body style=”margin:0;padding:0”>

<div id=”box” style=”top:10px;margin:20px 10px;”>

</div>

</body>

1.如果设置position: static ; 则上边距为        px

2.如果设置position: relative ; 则上边距为     px

3.如果设置position: absolute ; 则上边距为      px

4.如果设置position: sticky ; 则滚动起来上边距为   px

答案为:

position: static ; 则上边距为(  20 )px  静态定位 top值无效

position: relative ; 则上边距为(  30 )px 移动的时候会包括margin

position: absolute ; 则上边距为(  30 )px 移动的时候会包括margin

position: fixed ; 则上边距为(  30 )px  固定定位的margin也会生效  移动的时候也会包括margin

position: sticky ; 则上边距为(  20 )px,页面滚动起来为(10)px,margin会无效;页面没滚动的 时候是静态定位

原文地址:https://www.cnblogs.com/Catherine001/p/7244897.html