1. 程式人生 > >background屬性和position屬性

background屬性和position屬性

規則 css erl img ack pos 導致 不同 -a

最近看到一個頁面,當文本內容長時,背景不動,內容跟著變化,使用到了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會無效;頁面沒滾動的 時候是靜態定位

background屬性和position屬性