将CSS设置为div内部的img,其中div具有ID

时间:2015-09-19 06:27:08

标签: html css css-selectors

我有这段代码:



 .image-info > img {
    width:50px;
    height:50px;
    background-color:red;
}

<div id="special-image1">
    <div class="image-itself"></div>
    <div class="image-info">
        <img scr="" alt="SP1" width="248" height="78">
    </div>
</div>
<div id="special-image2">
    <div class="image-itself"></div>
    <div class="image-info">
        <img scr="" alt="SP2" width="248" height="78">
    </div>
</div>
&#13;
&#13;
&#13;

我想仅使用alt&#34; SP2&#34;更改img。另一个问题是代码有生成。我可以这样做吗?

感谢。

4 个答案:

答案 0 :(得分:0)

试试这个

Css代码:

img[alt="SP2"]{
   width: 50px;
   height: 50px;
   background-color:red;
}

OR

#special-image2 img {
   width: 50px;
   height: 50px;
   background-color:red;
}

答案 1 :(得分:0)

你正在寻找一个这样的选择器:

#special-image-2 img

img div id special-image-2 id

如果您因任何原因不想或不能使用div.image-itself div.image-info img[alt="SP2"] ,您也可以使用:

div

这会使alt类与img的{​​{1}}属性值相匹配。

但是,我会建议使用一个类来识别不同类型的图像元素供您使用,因为替代文本确实对上下文和可访问性有一个有效且重要的用途。

答案 2 :(得分:0)

我没有完全回答这个问题但请尝试.image-info > img[alt ="SP2"]

选择img元素alt vaue SP2

&#13;
&#13;
.image-info > img[alt ="SP2"] {
    width:50px;
    height:50px;
    background-color:red;
}
&#13;
<div id="special-image1">
    <div class="image-itself"></div>
    <div class="image-info">
        <img scr="" alt="SP1" width="248" height="78">
    </div>
</div>
<div id="special-image2">
    <div class="image-itself"></div>
    <div class="image-info">
        <img scr="" alt="SP2" width="248" height="78">
    </div>
</div>
&#13;
&#13;
&#13;

答案 3 :(得分:0)

我添加了一个重要的代码作品。 最后一个代码是:

 .image-info > img {
    width:50px;
    height:50px;
    background-color:green;
}
#special-image2 > .image-info > img {
    width:50px;
    height:50px;
    background-color:red !important;
}
<div id="special-image1">
    <div class="image-itself"></div>
    <div class="image-info">
        <img scr=""  width="248" height="78">
    </div>
</div>
<div id="special-image2">
    <div class="image-itself"></div>
    <div class="image-info">
        <img scr="" width="248" height="78" style="background-color:yellow;">
    </div>
</div>