开发者

How can I apply a style to a div using CSS as long as that div does NOT contain an element with a certain id?

I am writing a CSS stylesheet to add a background image to a div identified by its class name as follows:

.scrollingResultsContainer
{
    b开发者_StackOverflowackground-image: url(https://mdl0133/widget/Images/gradient.gif);
    background-repeat: repeat-x; 
    background-attachment: fixed;
    color:#FFFFFF;
}

This works fine except I have one particular situation where I do not want the image to appear in the scrollingResultsContainer. How can I specify that the image should be applied except when the scrollingResultsContainer happens to contain a div with a particular id?

Unfortunately, I am unable to amend the markup to prevent this situation from occurring. I was wondering if it can be done using CSS3 selectors.


You can't do this with CSS. A parent selector has been proposed many times but is always rejected because apparently it's just too hard to code or something: http://www.css3.info/shaun-inman-proposes-css-qualified-selectors/

You'll have to use javascript I'm afraid.


CSS4 might make this possible in the future, see http://davidwalsh.name/css4-preview.


Over-ride it in the CSS if you know the ID in advance.

.scrollingResultsContainer {
    font-size: 200%;
}

#id_of_div {
    font-size: normal;
}


If the only thing you want to do is prevent the image from showing up, this is fairly simple with CSS. You can use the ::before pseudo-element on the child <div> to cover the image and z-index to get the layers right.

Demo:

How can I apply a style to a div using CSS as long as that div does NOT contain an element with a certain id?

Output:

How can I apply a style to a div using CSS as long as that div does NOT contain an element with a certain id?

CSS:

.scrollingResultsContainer {
    background-image: url( 'http://placekitten.com/100' );
    border: 1px solid black;
    display: inline-block;
    height: 100px;
    position: relative;
    vertical-align: top;
    width: 100px;
    z-index: -2;
}
.dont-show::before {
    background-color: white;
    content: '';
    display: block;
    height: 100%;
    position: absolute;
    width: 100%;
    z-index: -1;
}

HTML:

<div class="scrollingResultsContainer"></div>
<div class="scrollingResultsContainer">
    <div class="dont-show">don't show</div>
</div>
<div class="scrollingResultsContainer"></div>
<div class="scrollingResultsContainer"></div>
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜