考慮你有一個固定身高和體重的div(在圖中最裏面的一個),並且你想讓周圍的div包含它, 1時。你會怎麼做?如何包裝這樣的div?
+--------+
| +-----+|
| |+---+||
| || |||
| |+---+||
| +-----+|
+--------+
考慮你有一個固定身高和體重的div(在圖中最裏面的一個),並且你想讓周圍的div包含它, 1時。你會怎麼做?如何包裝這樣的div?
+--------+
| +-----+|
| |+---+||
| || |||
| |+---+||
| +-----+|
+--------+
一種方法是使用inline-block
顯示樣式:
div { border: 1px solid blue; }
div.wrapper {
border: 1px solid red;
padding: 1em;
display: inline-block;
}
對於這個HTML:
<div class="wrapper">
<div class="wrapper">
<div style="width: 100px; height: 83px;">This</div>
</div>
</div>
這裏有一個例子:http://jsfiddle.net/redler/zSrXA/
您也可以嘗試打display: table-cell
。
哇,知道這真的很好。但是`inline-block`是做什麼的?我只知道`display:inline`和`display:block`。 – helpermethod 2011-02-02 20:27:53
它幾乎可以做到你想象的那樣。這是一個[很好的解釋](http://www.quirksmode.org/css/display.html#inlineblock)。 – 2011-02-02 20:59:43
見工作example here ..
<div class="margin1" id="div1"> </div>
<style>
.margin1
.margin1{
margin:1em;
border:1px solid red;
display:inline-block;
}
#div1{
height:40px;
width:20px;
}
</style>
然後使用jQuery來包裝div的要求..
$('#div1').wrap('<div class="margin1"/>').wrap('<div class="margin1"/>');
我的解決辦法是使用以下position:relative
:
HTML
<div id="first">
<div id="second">
<div id="third"></div>
</div>
</div>
CSS
div {position:relative;top:1.5em; left:1.5em}
#first {width:200px; height:200px; background:green}
#second {width:150px; height:150px; background:blue}
#third {width:100px; height:100px; background:black}
這裏是肯Redler的解決方案變體使用保證金,而不是填充(保證金境外,填充是車廂邊框) 。
div.inner
{
border: 1px solid blue;
margin: 1em;
}
div.outter
{
border: 1px solid red;
margin: 1em;
display: inline-block;
}
這裏是一個example fiddle
我喜歡你的顯示名稱。 :) – 2011-02-02 20:24:34