【问题标题】:Avoiding image objects to inherit styles dedicated to text formatting避免图像对象继承专用于文本格式的样式
【发布时间】:2018-10-24 01:06:40
【问题描述】:

这是我的第一篇文章:很尴尬,我记得几年前找到了解决我自己问题的方法……但是,让我们开始吧。

我为我的文本元素设置了一个完整的悬停/链接/活动 CSS

a:hover {
color: #000000;
background-color:#FFFF00;
font-weight: bold;
text-decoration: none;  
}

a:active {
color: #000000;
background-color:#FFFFFF;
font-weight: bold;
text-decoration: none;
}

a:link {
color: #FFFF00;
font-weight: bold;
text-decoration: underline; 
}

a:visited {
color: #000000;
background-color:#FFFFFF;
font-weight: bold;
text-decoration: none;
}  

问题是页面上的图片,带有它们自己的链接,也继承了上面的css。 第一次我想设置值border=0 会解决问题。我错了。 我只是在寻找最简单的方法来避免所有图像元素继承专用于链接文本格式的 css。

编辑:

我还尝试添加以下 css:

.img:active {
background-color: transparent;
}

.img:link {
background-color: transparent;
}

.img:hover {
background-color: transparent;
}

并将源代码中的图像元素与

class="img"

但图像继续继承主要的 css 样式。

编辑 2:

@andrea-ligios 您将 .img 类应用于包含图像的元素的建议非常有效!我还实现了 :not 选择器。太感谢了。抱歉,这是我的第一篇文章,我忘记了插入整个源代码会更容易找到解决方案。

【问题讨论】:

  • 我不太清楚你的意思,因为所有这些样式都与图像元素无关......但你可能在谈论大纲属性?
  • @ANML 答案是什么?在您的示例中的属性中,没有一个会影响 img 元素。除非图像不存在并且浏览器显示替代文本。
  • 您好 Temani,感谢您的回复。问题是,当我将链接关联到图像时,图像会继承我为文本编码的样式。我想避免这种情况。
  • @mr-lister 属性确实会影响图像元素。图片存在于同一页面上(都是透明png),例如当我将它们翻转时,它们会继承背景颜色效果。

标签: html css image css-selectors


【解决方案1】:

问题

问题在于页面上的图像,带有它们自己的链接,也继承了上面的 css。

所以你的 HTML(你应该总是和你的 CSS 一起发布,以防止我们做一些不必要的猜测工作)应该是这样的:

<a href="...">
   Some Text
</a>

<a href="...">
   <img src="..." />
</a>

对吗?

然后将源代码中的图像元素

class="img"

所以你已经尝试过了

<a href="...">
   <img class="img" src="..." />
</a>

?如果是这样,它就无法工作,因为您正在为 &lt;img&gt; 元素分配一个类,这与为 &lt;a&gt; 元素定义的要覆盖的规则无关。

解决方案

只需将.img 类应用于包含图像的&lt;a&gt; 元素:

<a class="img" href="...">
   <img src="..." />
</a>

由于class selectors have an higher specificity than element selectors.img 规则将覆盖a 规则。

也就是说,为什么不直接应用规则而不是使用 :not selector 覆盖它们?

a:not(.img):hover {
    color: #000000;
    background-color:#FFFF00;
    font-weight: bold;
    text-decoration: none;  
}
    
a:not(.img):active {
    color: #000000;
    background-color:#FFFFFF;
    font-weight: bold;
    text-decoration: none;
}
    
a:not(.img):link {
    color: #FFFF00;
    font-weight: bold;
    text-decoration: underline; 
}
    
a:not(.img):visited {
    color: #000000;
    background-color:#FFFFFF;
    font-weight: bold;
    text-decoration: none;
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2016-10-02
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-04-26
    • 1970-01-01
    相关资源
    最近更新 更多