1. 程式人生 > >CSS盒子模型和佈局

CSS盒子模型和佈局

CSS盒子模型

網頁設計中常聽的屬性名:內容(content)、內邊距(padding)、邊框(border)、外邊距(margin) CSS盒子模式都具備這些屬性。

這些屬性我們可以用日常生活中的常見事物——盒子作一個比喻來理解,所以叫它盒子模式。

CSS盒子模型就是在網頁設計中經常用到的CSS技術所使用的一種思維模型。

border:設定邊框     border:2px solid red;

(border-left:左邊框   border-right:右邊框   border-top:上邊框   

border-bottom:下邊框)

(none無邊框,solid邊框為實線,dotted邊框為點狀即點線,dashed邊框為虛線,double邊框為雙線)

padding :邊框內邊距   padding:20pax

padding-left:左內邊距

padding-right:右內邊距

padding-top:上內邊距

padding-bottom:下內邊距

margin:邊框外邊距       margin:20px

margin-left:左外邊距

margin-right右外邊距

margin-top上外邊距

margin-bottom下外邊距

對資料進行操作,需要把資料放到一個區域裡面(div)

佈局的漂浮

     float

float 屬性定義元素在哪個方向浮動。以往這個屬性總應用於影象,使文字圍繞在影象周圍,不過在

CSS 中,任何元素都可以浮動。浮動元素會生成一個塊級框,而不論它本身是何種元素。

如果浮動非替換元素,則要指定一個明確的寬度;否則,它們會盡可能地窄。

例項

把影象向右浮動:

<html>
<head>
<style type="text/css">
img
{
float:right
}
</style>
</head>
<body>
<p>在下面的段落中,我們添加了一個樣式為 <b>float:right</b> 的影象。結果是這個影象會浮動到段落的右側。</p>
<p>
<img src="/i/eg_cute.gif" />
This is some text. This is some text. This is some text.
This is some text. This is some text. This is some text.
This is some text. This is some text. This is some text.
This is some text. This is some text. This is some text.
This is some text. This is some text. This is some text.
This is some text. This is some text. This is some text.
This is some text. This is some text. This is some text.
This is some text. This is some text. This is some text.
This is some text. This is some text. This is some text.
This is some text. This is some text. This is some text.
</p>
</body>
</html>

效果:

佈局的定位

position 屬性規定元素的定位型別。

absolute

生成絕對定位的元素,相對於 static 定位以外的第一個父元素進行定位。

元素的位置通過 "left", "top", "right" 以及 "bottom" 屬性進行規定。

fixed

生成絕對定位的元素,相對於瀏覽器視窗進行定位。

元素的位置通過 "left", "top", "right" 以及 "bottom" 屬性進行規定。

relative

生成相對定位的元素,相對於其正常位置進行定位。

因此,"left:20" 會向元素的 LEFT 位置新增 20 畫素。

static

預設值。沒有定位,元素出現在正常的流中(忽略 top, bottom, left, right 或者 z-index 宣告)。

例項 絕對定位

<html>
<head>
<style type="text/css">
h2.pos_abs
{
position:absolute;
left:100px;
top:150px
}
</style>
</head>
<body>
<h2 class="pos_abs">這是帶有絕對定位的標題</h2>
<p>通過絕對定位,元素可以放置到頁面上的任何位置。下面的標題距離頁面左側 100px,距離頁面頂部 150px。</p>
</body>
</html>

效果:

例項 相對定位

<html>
<head>
<style type="text/css">
h2.pos_left
{
position:relative;
left:-20px
}
h2.pos_right
{
position:relative;
left:20px
}
</style>
</head>
<body>
<h2>這是位於正常位置的標題</h2>
<h2 class="pos_left">這個標題相對於其正常位置向左移動</h2>
<h2 class="pos_right">這個標題相對於其正常位置向右移動</h2>
<p>相對定位會按照元素的原始位置對該元素進行移動。</p>
<p>樣式 "left:-20px" 從元素的原始左側位置減去 20 畫素。</p>
<p>樣式 "left:20px" 向元素的原始左側位置增加 20 畫素。</p>
</body>
</html>

效果: