css樣式總結

1、利用text-align:center讓子元素居中,子元素應爲行內元素或行間塊狀元素。

2、利用width和margin水平居中,需要設置寬度和margin-left:auto、margin-right:auto,行間元素不能設置寬度所以無法居中

<div style="background-color:red;height:300px;">
	<div style="backgroundcolor:blue;height:100px;margin:auto;width:200px;display:inline">	
	nnnnnnnnnnnn
	</div>
</div>

3、利用雙重定位實現水平居中。父元素絕對定位,left:50%;子元素相對定位,right:50%;這能自適應寬度。

<div style="background-color:red;position:absolute;left:50%">
	<div style="background-color:blue;height:100px;width:200px;position:relative;right:50%">
	
	jjjSnnnnnnnnnnnn
	
	</div>	
</div>

4、使用display:table-cell來居中,模擬一個表格單元格,父元素需要設置寬度,子元素需要設置爲行間塊狀元素,可以自適應寬度。

<div style="background-color:red;display:table-cell;text-align:center;width:500px;">
	<div style="background-color:blue;height:100px;width:150px;display:inline-block">
	
	jjjSnnnnnnnnnnnn
	
	</div>
	
</div>

5、利用負margin和定位,這需要設置子元素寬度,left:50%,margin-left:width/2。

<div style="background-color:red;height:500px;">
	<div style="background-color:blue;height:100px;width:200px;position:relative;left:50%;margin-left:-100px;">
	
	jjjSnnnnnnnnnnnn
	
	</div>
	
</div> 

6、浮動,絕對定位,固定定位後,元素都是行間塊狀元素,但是相對定位還是原來的屬性。

7、絕對定位後,left、height等設爲百分比時,是相對瀏覽器的百分比,而不是其父容器;但是相對定位就是其父容器的百分比;絕對定位是其第一個非static定位的祖先元素。

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章