2014-12-02 40 views
0

什麼是適用於不同的背景顏色到同一元素的正確方法? 例如相同的元素在CSS中不同的顏色

<div id="mainmenumess"> 
    <p class="incmessage">must be blue</p> 
    <p class="incmessage">must be red</p> 
</div> 

CSS

#mainmenumess .incmessage{ 
-webkit-border-radius: 5; 
-moz-border-radius: 5; 
border-radius: 5px; 
color: #ffffff; 
background: #de2424; 
padding: 0px 5px 0px 5px; 
text-decoration: none; 
cursor:pointer; 
} 

#mainmenumess .incmessage:hover { 
background: #ed4747; 
text-decoration: none; 
} 

如果是紅色必須懸停藍色不要有懸停

回答

1

有沒有「正確」的方法有很多。根據哪些瀏覽器必須支持並總是有內部<div>只是恰好兩個<p>元素或可能有更多...

這是一個 - >http://jsfiddle.net/0p3mxqgx/

<div id="mainmenumess"> 
    <p class="incmessage">must be blue</p> 
    <p class="incmessage">must be red</p> 
</div> 

#mainmenumess .incmessage { 
    -webkit-border-radius: 5; 
    -moz-border-radius: 5; 
    border-radius: 5px; 
    color: #ffffff; 
    background: #de2424; 
    padding: 0px 5px 0px 5px; 
    text-decoration: none; 
    cursor:pointer; 
} 
#mainmenumess .incmessage:first-child { 
    background:blue; 
} 
#mainmenumess .incmessage:hover { 
    background:blue; 
    text-decoration: none; 
} 
#mainmenumess .incmessage:first-child:hover { 
    background:red; 
} 

這是另一種:使用oddeven - >http://jsfiddle.net/0p3mxqgx/1/

#mainmenumess .incmessage { 
    -webkit-border-radius: 5; 
    -moz-border-radius: 5; 
    border-radius: 5px; 
    color: #ffffff; 
    background: #de2424; 
    padding: 0px 5px 0px 5px; 
    text-decoration: none; 
    cursor:pointer; 
} 
#mainmenumess .incmessage:nth-child(odd) { 
    background:blue; 
} 
#mainmenumess .incmessage:nth-child(even):hover { 
    background:blue; 
    text-decoration: none; 
} 
#mainmenumess .incmessage:nth-child(odd):hover { 
    background:red; 
} 
2

你會使用nth-child

.incmessage:nth-child(1) { background-color: blue; } 
.incmessage:nth-child(1):hover { background-color: red; } 

.incmessage:nth-child(2) { background-color: red; } 
.incmessage:nth-child(2):hover { background-color: blue; } 

雖然,我會考慮添加類的元素,導致這看起來很粗糙。

這不會在< = IE8中工作。

2

那麼從它的聲音來看,第一個是紅色的,其他所有的都是藍色的?你會想要做這樣的事情:

1

你可以用第n個孩子或圖案

在這裏,我已經使用2N模式爲奇者和2N + 1找齊

#mainmenumess .incmessage{ 
 
-webkit-border-radius: 5; 
 
-moz-border-radius: 5; 
 
border-radius: 5px; 
 
color: #ffffff; 
 

 
padding: 0px 5px 0px 5px; 
 
text-decoration: none; 
 
cursor:pointer; 
 
} 
 

 
#mainmenumess .incmessage:hover { 
 
background: #ed4747; 
 
text-decoration: none; 
 
} 
 
#mainmenumess .incmessage:nth-child(2n) { background-color: blue; } 
 
#mainmenumess .incmessage:nth-child(2n+1) { background-color: red; } 
 

 
#mainmenumess .incmessage:nth-child(2n):hover { background-color: red; } 
 
#mainmenumess .incmessage:nth-child(2n+1):hover { background-color: blue; }
<div id="mainmenumess"> 
 
    <p class="incmessage">must be blue</p> 
 
    <p class="incmessage">must be red</p> 
 
    <p class="incmessage">must be red</p> 
 
    <p class="incmessage">must be red</p> 
 
</div>
選擇