以下代码是使用bootstrap的html文件的一部分。主要是我想要设置<a>
的样式.navbar-brand
。为此,我向.grandchildlink
添加了另一个类<a>
(不要注意名称)。问题是它不能以这种方式工作..,两个替代方案是:
1。使用后代选择器,例如。使用.parentbody
的课程<body>
,然后使用.parentbody .grandchildlink:hover, .parentbody .grandchildlink:focus{...}
)
2. 向<a>
添加id属性说:grandchildlink_id
然后(#grandchildlink_id:hover, #grandchildlink_id:focus {...}
)
..,问题是为什么不使用一个类选择器?
.
.
.
<style type="text/css">
.grandchildlink:hover, .grandchildlink:focus {
background-color: transparent;
color: yellow;
}
</style>
</head>
<body class="parentbody">
<div class="navbar navbar-default navbar-fixed-top navbar-inverse">
<div class="container">
<button type="button" class="navbar-toggle" data-toggle="collapse" data-target=".navbar-collapse">
<span class="sr-only">Toggle naviagation</span>
<span class="icon-bar"></span>
<span class="icon-bar"></span>
<span class="icon-bar"></span>
</button>
<a href="#" class="grandchildlink navbar-brand" >BrandName</a>
<div class="navbar-collapse collapse">
<ul></ul>
</div>
</div>
</div>
.
.
.
答案 0 :(得分:2)
因为css specificity。这是CSS bootstrap使用的。
.navbar-inverse .navbar-brand:focus, .navbar-inverse .navbar-brand:hover {
color: #fff;
background-color: transparent;
}
这意味着要覆盖它,你需要使用.navbar-inverse .grandchildlink {}
或相等的东西(只要你的样式来自bootstrap.css之后)或更高的特异性,就像你在例子中列出的那样。
<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet"/>
<style>
.navbar-inverse .grandchildlink:hover, .navbar-inverse .grandchildlink:focus {
background-color: transparent;
color: yellow;
}
</style>
<body class="parentbody">
<div class="navbar navbar-default navbar-fixed-top navbar-inverse">
<div class="container">
<button type="button" class="navbar-toggle" data-toggle="collapse" data-target=".navbar-collapse">
<span class="sr-only">Toggle naviagation</span>
<span class="icon-bar"></span>
<span class="icon-bar"></span>
<span class="icon-bar"></span>
</button>
<a href="#" class="grandchildlink navbar-brand">BrandName</a>
<div class="navbar-collapse collapse">
<ul></ul>
</div>
</div>
</div>
&#13;