css 有時候會很棘手,尤其是在定位和設置大小的時候。本文包含了我整理的一系列有用的片段,它們使我的生活變得更容易,希望也能幫到你們。
注:每個段落的下方有一個表,說明瀏覽器的支持情況。
動態(tài)調整大小的元素。
.parent { position: relative; }
.child {
position: absolute;
left: 50%;
top: 50%
-webkit-transform: translate(-50%, -50%);
-moz-transform: translate(-50%, -50%);
-ms-transform: translate(-50%, -50%);
-o-transform: translate(-50%, -50%);
transform: translate(-50%, -50%);
}
固定大小的元素。
.parent { position: relative; }
.child {
position: absolute;
left: 50%;
top: 50%
height: 250px;
width: 500px;
/* Translate element based on it's size */
margin-left: -125px;
marign-top: -250px;
}
隨著百分比變化的
.parent { position: relative; }
.child {
position: absolute;
height: 50%;
width: 50%;
left: 25%; /* (100% - width) / 2 */
top: 25%; /* (100% - height) / 2 */
}
塊級元素的寬度值。
.block {
margin-left: auto;
margin-right: auto;
}
內聯(lián)和內聯(lián)塊元素
.parent { text-align: center; }
.child { display: inline-block; }
靜態(tài)父元素中的內聯(lián)和內聯(lián)塊元素
.parent { line-height: 500px; }
.child {
display: inline-block;
vertical-align: middle;
}
偽表格
.parent { display: table; }
.child {
display: table-cell;
vertical-align: middle;
}
下面創(chuàng)建一個全尺寸的塊元素,但是因為有邊框,內邊距與外邊距而沒有成功。盒模型的屬性使它沒有成為預期的大小。
html { min-height: 100%; }
body { height: 100%; }
.block {
height: 100%;
width: 100%;
-webkit-border-sizing: border-box;
-moz-border-sizing: border-box;
border-sizing: border-box;
}
接下來的代碼創(chuàng)建一個全尺寸的塊元素為全屏幕,不依賴于邊框和內邊距。你可以為某個模塊設定值來創(chuàng)建空間,比如標頭。
html { min-height: 100%; }
body { height: 100%; }
.center {
position: absolute; /* or fixed */
bottom: 0;
left: 0;
right: 0;
top: 0; /* top: 50px; would reserve 50px for an header */
}
接下來我們創(chuàng)建一個絕對元素總是等于或大于視窗,基于文檔的高度
html {
position: relative;
min-height: 100%;
}
body { height: 100%; }
.block {
min-height: 100%;
position: absolute;
}
在這里討論的所有方法幾乎都可以通過嵌套來組合它們。你還知道其他很棒的技巧或有用的代碼么?來這里分享吧!
更多建議: