2013-09-25 71 views
3

我想弄清楚如何做到這一點,基本上我有兩個元素。當一個元素低於另一個元素時,CSS會在元素之間添加空間?

<div class="button">This is the first one</div> 
<div class="button">This is the second one</div> 

有時兩者都彼此相鄰,在這種情況下,我確定他們的造型。

enter image description here

但是,如果第二個「倒下」由於父母過於狹隘,我不希望兩個元素互相接觸。

enter image description here

我的問題是,加入底邊距的元素也將影響情況1(當它們彼此相鄰),我不想做的事。當一個在另一個之下時,我怎樣才能將這兩個元素分開?

Jsfiddle(試行擴縮的結果框)

回答

2

一個非常簡單的解決方案將使用negative padding值,但由於這是不可能的,我們可以使用另一種簡單的方法,即使它有點散步。您可以用另一個包裝元素包裝容器,併爲該容器提供負值0​​值。

jsFiddle Demo

HTML:

<div class="wrapper"> 
    <div class="container"> 
     <div class="button">This is the first button</div> 
     <div class="button">This is the second button</div> 
    </div> 
</div> 

CSS:

.wrapper { 
    overflow: hidden; 
} 
.container { 
    margin-top: -10px; 
} 
.button { 
    margin-right: 10px; 
    margin-top: 10px; 
} 
+1

1+一個很好的解決方案。在*框外思考的好方法* –

0

這可能沒有太大的幫助,但我想無論是確保該按鈕只有跌破彼此在不同的屏幕寬度的情況下(在這種情況下,我可以通過@media查詢來解決這個問題),或者添加一些頂部/底部邊距,並使其他元素進行補充。

+0

我可能會迫使它們落,加入300像素一個最小寬度低於600px的......這是不是一個壞主意。如果沒有其他出來,我會採取這個想法 – lisovaccaro

0

這可以通過使用媒體查詢http://css-tricks.com/css-media-queries/來實現。基本上,您可以控制當視口低於或高於特定寬度時應用哪些規則。我已經分叉你的代碼來添加一個基於520px寬視口的媒體查詢,但是你可以根據你的需要進行調整。

在這裏找到的代碼(CSS):

.background{ 
    background: red; 
    display: inline-block; 
} 
.button{ 
    background: orange; 
    padding: 10px; 
    display: inline-block; 
    margin-right: 10px; 
    width: 200px; 
} 
@media all and (max-width: 520px){ 
    .button{ 
     margin: 0 0 10px 0; 
    } 
    .background{ 
     width: 220px; 
    } 
} 

和HTML:

<div class="background"> 
    <div class="button">This is the first button</div> 
    <div class="button">This is the second button</div> 
</div> 

歧路小提琴可以在這裏找到:http://jsfiddle.net/vsYpe/1/

希望這有助於!

0

我不確定是否有更好的方式來使用CSS,但如果沒有其他的工作,第一個元素下方的不可見元素可以工作?我不確定你的情況,但是如果你給我們更多的細節,可能還有其他的選擇。

相關問題