在元素父级中应用css但在子级中不应用css

时间:2015-09-27 19:05:48

标签: css

我想让包含img元素的第3行也是绿色的,怎么办?

<div style="padding-top:5px;">

    <div class="right">line 1</div>
    <div class="right">line 2</div>
    <div class="right">
        <img src="https://upload.wikimedia.org/wikipedia/ro/f/f7/Stack_Overflow_logo.png"></img>
    </div>
    <div class="right">line 4</div>
    <div class="right">line 5</div>    
</div>

.right {
    background-color: red;
}

.right > img {
    background-color: green;
}

fiddle

PS。 IMG元素动态显示,不可预测..

3 个答案:

答案 0 :(得分:2)

使用jquery&gt;&gt;的解决方案solution

$("img.img-thumbnail").parents('div.right').css("background-color", "green");

答案 1 :(得分:0)

添加以下css:

.right:nth-child(3) {
    background-color:green;
}

cast the return value from malloc()

答案 2 :(得分:0)

jsfiddle demo

//HTML
<div class="wrapper">
    <div class="right">line 1</div>
    <div class="right">line 2</div>
    <div class="right">
        <div class="image">
            <img src="https://upload.wikimedia.org/wikipedia/ro/f/f7/Stack_Overflow_logo.png"></img>
        </div>
    </div>
    <div class="right">line 4</div>
    <div class="right">line 5</div>    
</div>

//CSS
.wrapper{
    padding-top:5px;
    background-color: red;
}
.right {
    width: 100%;
}
.image {
    background-color: green;    
}

编辑: OP可以使用jQuery解决方案,managed to find that answer himself

$("img.img-thumbnail").parents('div.right').css("background-color", "green");

Alternativ解决方案也是;     $("img.img-thumbnail").parents('div.right').addClass('green');

//CSS
.green {
    background-color: green;    
}