如何在<a> tag?

时间:2018-07-27 06:30:46

标签: html css

Here's some code that contains a tags, one which contains an image.

<div class="container">
    <a href="#">Not styled</a>
    <a href="#"><img src="image.png"></a>
</div>

If I only want to style the image, how would I do it (without creating a class or something similar)?

For example, if I want to style all the a tags, I could use the following CSS:

.container a {
    /* styles here */
}

If I want to style all the img tags, I could use this:

.container img {
    /* styles here */
}

Is there a way to apply this same logic to an img in an a tag?

Edit: Here are the styles I'm applying. For some reason, when I use .container a img it adds extra padding/margins.

.container a {
    padding: 9px 10px 5px 10px;
}

Edit 2: I think the problem lies elsewhere. Whenever I try any of the suggested responses (i.e. .container a img, #img, src="image.png") they all lead to the amount of vertical padding/margin increasing. Should I delete my post? It seems all it is getting is downvotes right now.

7 个答案:

答案 0 :(得分:1)

您可以创建嵌套的CSS

.container a img {
    /* styles here */
}

答案 1 :(得分:1)

是的,您可以这样做,看一下演示,它将应用于a标签下的所有图像

.container a img {
    /* styles here */
}

如果您只想将单个图像应用于CSS,请尝试为其指定ID,然后将CSS应用于ID

适用于所有人的演示

.container a img{
    filter: sepia(100%);
}
<div class="container">
    <a href="#">Not styled</a>
    <a href="#"><img src="https://www.whistler.com/images/placeholders/200x200.gif" /></a>
    <a href="#"><img src="https://www.whistler.com/images/placeholders/200x200.gif" /></a>
</div>

适用于单个ID的演示

#img{
    filter: invert(100%);
}
<div class="container">
    <a href="#">Not styled</a>
    <a href="#"><img src="https://www.whistler.com/images/placeholders/200x200.gif" /></a>
    <a href="#"><img src="https://www.whistler.com/images/placeholders/200x200.gif" id='img' /></a>
</div>

答案 2 :(得分:1)

.container a img {}是执行此操作的最佳方法,但是每个IMG都会使用您在.container a {padding: etc }中指定的填充/边距。因此,请尝试将IMG留在边缘。

答案 3 :(得分:0)

我认为您可以简单地使用CSS来精确指向如下图像:

img[src="image.png"]{

}

答案 4 :(得分:0)

您的问题:如果我只想为图像设置样式,我将如何做(不创建类或类似的东西)?

现在,如果您只希望该特定图像没问题,但是如果以后越来越多的图像以相同的方式运行,则最好创建一个类 注意:您没有指定要用于图像的样式,所以我假设您需要此样式 填充:9px 10px 5px 10px

<div class="container">
    <a href="#">Not styled</a>
    <a href="#"><img style="padding: 9px 10px 5px 10px;" src="image.png">YES styled</a>
</div>

答案 5 :(得分:0)

为图像提供一个单独的类,然后在CSS中对其进行样式设置

答案 6 :(得分:-1)

您只需要编写层次结构为的CSS

.container a img {
// your code
}