html - 我如何为 div 中的链接添加不同的样式并向其添加类?

标签 html css css-specificity

我在 div 中有多个 div,类为 .grid。在那些 div 中,我在每个中都有一个链接。我使用选择器 .grid div a 设置了这些链接的样式。之后我在每个 div 中添加了另一个链接,并给它一个类 .name 并使用 .grid div .name 选择它。问题是这些带有类名的新链接受到级联的影响。为什么会这样? .grid div .name 选择器更具体对吧? 这是我的 CSS 这是为了将 div 变成可点击的链接

.grid div a
{
position:absolute;
width: 100%;
height: 100%;
top:0;
left:0;
text-decoration: none;
z-index: 1;
}
This is the style for the other links
.grid div.name
{
position: absolute;
height: 20px;
width: 120px;
font-family: lato;
color:  #424242;
}

Click for image

最佳答案

This is the style for the other links

.grid div.name

不,不是!

这将是:

.grid div a.name

.grid div .name

.grid div a.name {
  background: pink;
}
<div class="grid">
  <div>
    <a href="#1">First Link</a>
    <a href="#2" class="name">Name Link</a>
  </div>
</div>

您当前的选择器选择具有类名称的 div,因为元素类型和类之间没有“空格”

关于html - 我如何为 div 中的链接添加不同的样式并向其添加类?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38790525/

相关文章:

css - 如何查看浏览器计算的CSS特异性?

css - 将 CSS 颜色应用于文本输入,但仍然可以用类覆盖它

html - 将鼠标悬停在 div 上不影响 div

python - 如何解决 selenium webdriver 中的斜线问题?

html - 如何对齐到中心 float 的 div?

javascript - Localstorage 选择 Javascript - 保存样式 CSS

html - Bootstrap 导航栏中的下拉菜单

javascript - CSS 过渡不适用于 classList.add

css - less 中的嵌套样式,样式父级和子级

基于样式表中顺序的 CSS 特异性/优先级?