2013-08-28 33 views
2

我想知道是否有方法在CSS中設置「響應邊距」。 這裏是我的意思的說明:如何在css中設置一個響應邊距(關於應用元素的寬度/高度)?

<div style="width:100%;"> 

    <div style="width:18%; margin:0 1%;"> 
    <div style="width:18%; margin:0 1%;"> 
    <div style="width:18%; margin:0 1%;"> 
    <div style="width:18%; margin:0 1%;"> 
    <div style="width:18%; margin:0 1%;"> 

</div> 

我想margin足夠聰明,已瞭解「我希望width的1%」和top/bottom應用height的0%。

不幸的是,這不是默認行爲,所以你如何管理它?其實我正在使用JavaScript,但我想優化我的perfs。

+0

除非它只是在這個例子中,_please_招你的樣式出來到外部樣式表,並使用一些類/ ID – Bojangles

+0

順便說一句,什麼是1%?外部div的寬度或其中一個內部div的寬度? – biziclop

回答

0

根據這一http://mattsnider.com/css-using-percent-for-margin-and-padding/

如果設置保證金或百分比填充是父元素的寬度百分比,所以你可以做

<div style="width:100%; height: 100px;"> 

    <div style="width: 18%"><div style="padding: 0 10%"><div style="width:100%; height: 20px;"></div></div></div> 
     <div style="width: 18%"><div style="padding: 0 10%"><div style="width:100%; height: 20px;"></div></div></div> 
     <div style="width: 18%"><div style="padding: 0 10%"><div style="width:100%; height: 20px;"></div></div></div> 
     <div style="width: 18%"><div style="padding: 0 10%"><div style="width:100%; height: 20px;"></div></div></div> 

    </div> 

而在這一點,你必須使用箱 - 尺寸:邊框

無法寬度包含:內部寬度+填充+邊框+邊距

一個例子http://jsfiddle.net/98FGe/2/

0

假設這HTML代碼:

<div class="wrap"> 
    <div class="item"></div> 
    <div class="item"></div> 
    <div class="item"></div> 
    <div class="item"></div> 
    <div class="item"></div> 
</div> 

...你可以 「floatize」 他們: http://jsfiddle.net/3rwhd/2/

.wrap { 
    width: 100%; 
} 

.item { 
    float: left; 
    width: 18%; 
    margin: 0 1%; 
} 

...或「inline-block的理由「他們(如果你不想要外邊距): http://jsfiddle.net/3rwhd/1/

.wrap { 
    width: 100%; 
    text-align: justify; 
} 

/* this element will force justificaton */ 
.wrap:after { 
    content:''; 
    display: inline-block; 
    width: 90%; 
    height: 0; 
} 

.item { 
    display: inline-block; 
    width: 18%; 
} 

...或 「表>表芯」 他們: http://jsfiddle.net/3rwhd/3/

HTML:

<div class="wrap"> 
    <div class="item"><div></div></div> 
    <div class="item"><div></div></div> 
    <div class="item"><div></div></div> 
    <div class="item"><div></div></div> 
    <div class="item"><div></div></div> 
</div> 

CSS:

.wrap { 
    display: table; 
    width: 100%; 
} 

.item { 
    display: table-cell; 
    vertical-align: top; 
    width: 20%; 
} 

.item > div { 
    display: block; 
    margin: 0 1%; 
} 

/* optional; remove outer margins */ 

.item:first-child > div { 
    margin-left: 0; 
} 

.item:last-child > div { 
    margin-right: 0; 
} 
相關問題