css的position屬性有哪些?css中position屬性及用法的介紹

來源:互聯網
上載者:User
本篇文章給大家帶來的內容是關於css的position屬性有哪些?css中position屬性及用法的介紹,有一定的參考價值,有需要的朋友可以參考一下,希望對你有所協助。

position 屬性介紹

(1)css中position 屬性自 CSS2 起就有了,該屬性規定元素的定位類型。所有主流瀏覽器都支援 position 屬性。

(2)css中position屬性的可選值有四個:static、relative、absolute、fixed。下面分別進行介紹。(其實還有個 inherit,不過這個是 IE 特有的,這裡就不做討論)

<h3 id="position: static(預設值)"> position: static(預設值)</h3>

1,基本介紹
(1)static 是預設值。表示沒有定位,或者說不算具有定位屬性。
(2)如果元素 position 屬性值為 static(或者未設 position 屬性),該元素出現在正常的流中(忽略 top, bottom, left, right 或者 z-index 聲明)。

2,使用範例

css:

<style>  div {    width: 200px;    height: 100px;    background-color: #C9FFFF;  }</style>

html:

<div></div><input type="text"/>

我們不設定元素的 postion 屬性值,那麼預設的顯示效果如下:

<div class="position-static"></div> <input type="text"/><h3 id="position: relative(相對定位)"> position: relative(相對定位)</h3>

1,基本介紹

(1)relative 產生相對定位的元素,相對於其正常位置進行定位。
(2)相對定位完成的過程如下:

首先按預設(static)產生一個元素(並且元素像層一樣浮動了起來)。
然後相對於以前的位置移動,移動的方向和幅度由 left、right、top、bottom 屬性確定,位移前的位置保留不動。

2,範例代碼

下面代碼將文本輸入框 position 設定為 relative(相對定位),並且相對於預設的位置向右、向上分別移動 15 個像素。

css:

  div {    width: 200px;    height: 100px;    background-color: #C9FFFF;  }     input {    position: relative;    left: 15px;    top: -15px;  }

html:

<div></div><input type="text" />

運行效果如下:

1,基本介紹

(1)absolute 產生絕對位置的元素。
(2)絕對位置的元素使用 left、right、top、bottom 屬性相對於其最接近的一個具有定位屬性的父元素進行絕對位置。
(3)如果不存在這樣的父元素,則相對於 body 元素,即相對於瀏覽器視窗。

2,範例代碼

下面代碼讓標題元素相對於它的父容器做絕對位置(注意父容器 position 要設定為 relative)。
同時通過 top 屬性讓標題元素上移,使其覆蓋在父容器的上邊框。
最後通過 left 和 margin-left 配合實現這個絕對位置元素的水平置中。

css:

  #box {    width: 200px;    height: 100px;    -webkit-box-flex:1;    border: 1px solid #28AE65;    border-radius:6px;    padding: 20px;    position: relative;    font-size: 12px;  }   #title {    background: #FFFFFF;    color: #28AE65;    font-size: 15px;    text-align: center;    width: 70px;    height: 20px;    line-height: 20px;    position: absolute;    top: -10px;    left: 50%;    margin-left: -35px;  }

html:

<div id="box"> <div id="title">標題</div> 歡迎來到php中文網</div>

運行效果如下:

1,基本介紹
(1)fixed 產生絕對位置的元素,該元素相對於瀏覽器視窗進行定位。
(2)固定定位的元素不會隨瀏覽器視窗的捲軸滾動而變化,也不會受文檔流動影響,而是始終位於瀏覽器視窗內視圖的某個位置。

2,範例代碼
(1)下面代碼讓輸入框位於瀏覽器視窗的底部。

css:

  input {    position: fixed;    bottom: 10px;  }

html:

<ol> <li>資料</li><li>資料</li><li>資料</li><li>資料</li><li>資料</li><li>資料</li> <li>資料</li><li>資料</li><li>資料</li><li>資料</li><li>資料</li><li>資料</li> <li>資料</li><li>資料</li><li>資料</li><li>資料</li><li>資料</li><li>資料</li> <li>資料</li><li>資料</li><li>資料</li><li>資料</li><li>資料</li><li>資料</li></ol><input type="text" />

運行效果如下:

(2)可以看到不管捲軸如何滾動,輸入框始終處於視窗的最下方。

相關文章

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.