相同的元素在CSS中不同的颜色
问题描述:
什么是适用于不同的背景颜色到同一元素的正确方法? 例如相同的元素在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;
}
如果是红色必须悬停蓝色不要有悬停
答
有没有“正确”的方法有很多。根据哪些浏览器必须支持并总是有内部<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;
}
这是另一种:使用odd
和even
- >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;
}
答
你会使用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中工作。
答
那么从它的声音来看,第一个是红色的,其他所有的都是蓝色的?你会想要做这样的事情:
答
选择
你可以用第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>