2017-08-08 73 views
1

我想將margin-top樣式添加到.three,但前提是.one.twoCSS樣式的子div,但只有父母有以下兄弟

.one { 
 
    background: indianred; 
 
    height: 100px; 
 
    width: 100px; 
 
} 
 

 
.three { 
 
    background: bisque; 
 
    height: 100px; 
 
    width: 100px; 
 
} 
 

 
.one .two + .three { 
 
    margin-top: 20px; 
 
}
<div class="one"> 
 
    <div class="two">hello</div> 
 
</div> 
 
<div class="three">there</div> 
 

 

 
<div class="one"> 
 
</div> 
 
<div class="three">there</div>

Fiddle

可以這樣做?感謝幫助。

+1

單獨使用CSS這是不可能的,但使用JavaScript會很簡單。 – APAD1

+1

CSS無法上父。所以這對於純CSS來說是不可能的。 –

+0

有一天[:has](https://developer.mozilla.org/en-US/docs/Web/CSS/:has)可以:P – Vucko

回答

2

據我所知,最近你可以得到的是扭轉邏輯和使用:empty。這是一個可憐的替代品,可能不會滿足您的需求,但它可以工作 - 在正確的情況下。

.one { 
 
    background: indianred; 
 
    height: 100px; 
 
    width: 100px; 
 
} 
 
.three { 
 
    background: bisque; 
 
    height: 100px; 
 
    width: 100px; 
 
    margin-top: 20px; 
 
} 
 

 
.one:empty + .three { 
 
    margin-top: 0; 
 
}
<div class="one"> 
 
    <div class="two">hello</div> 
 
</div> 
 
<div class="three">there</div> 
 

 

 
<div class="one"></div><!-- Note how .one is completely empty with not even a newline --> 
 
<div class="three">there</div>

這有點作弊不過,因爲它不檢查,看看是否有.one.two。相反,它假定.one確實有一個孩子,那個孩子是.two。如果.one沒有孩子,則不應用保證金。這是大量的假設,大部分時間是無用的,除非你可以做出相同的假設。

你可以使用這個唯一的辦法是,如果你知道.two是唯一可能的孩子,如果.one沒有.two那麼它將永遠都沒有了。沒有空格,換行符或其他任何可以算作孩子的地方(註釋是安全的)。

一個很好的方法來看看你是否可以使用這個(或類似的)是試圖重寫你的邏輯。如果'添加保證金頂部到.three,但只有當.one有一個.two'可以重寫爲'從.three刪除保證金頂部,但只有在.one爲空'的情況下,此方法纔有效。根據你實際需要,可能有其他方法來重新考慮你的邏輯到當前可行的東西。

相關問題