开发者

Style list items in a certain div

I have a div structure like the bottom:

<div class="body-content">
  <div class="col-middle">

  </div>
</div>

What I want to do is set a style on list items within the body-content class and make sure it does not apply to anything within col-middle

I thought it would be something like...

.body-content li {开发者_如何转开发 }

but it applies those styles to list items within col-middle too.


The simplest and most backwards compatible option is:

div.body-content li { /* some style */ }
div.col-middle li { /* some other style */ }

You might be able to use the child selector:

div.body-content > ul li

but it's not supported in IE6.

Other than that, it depends on exactly how your markup is written and what your requirements with respect to browser support are.

If possible, change your markup to:

<div class="body-content">
  <div class="col-middle">
  ...
  </div>
  <div class="col-other">
  ...
  </div>
</div>

or something similar so you can easily distinguish between which list you want to style.


I would then ZERO out the .body-content .col-middle li { }'s AFTER styling the .body-content li { }'s

Your only other option is to specify where the li is going to be:

.body-content .li-block li { }


The code you tried specifies how list items ONLY inside .body-content should look, even if they are inside .col-middle.

Using CSS2 there isn't any way to do what you want, appart from specifying how list items outside .col-middle should work, and then specifying how they should be styled inside .col-middle.

Using CSS3 however, you can do something like this:

:not(.col-middle) li{}

Note that this does not work in any IE browsers.


You need:

.body-content > ul li { ... }

This will only select list items that are direct descendants of a ul in .body-content.

Edit: Ooops, wrong place for the > !

Edit: Sorry, also should have mentioned - child selectors don't work in IE6.


You should use, which will put the style only for the sons li of .body-content

.body-content > ul li {}


Restyle the col-middle.

div.body-content li {
  color: red;
}

div.col-middle li {
  // overrides stuff
  color: black;
}

Styles cascade on down from parent elements to their children.


The example below seems to work the best (I've added some extra markup to demonstrate this), but I'd recommend styling .body-content and then override those styles in .col-middle. It would be the most cross-browser compatible.

<!DOCTYPE html>

<html>
<head>
<title></title>
<style type="text/css">
.body-content > *:not(.col-middle) li {
    color: red;
}
</style>
</head>
<body>

<div class="body-content">
  <div class="col-middle">
    <ul>
        <li>item 1</li>
        <li>item 2</li>
    </ul>
  </div>

  <div>
    <ul>
        <li>item 1</li>
        <li>item 2</li>
    </ul>
  </div>

  <ul>
    <li>item 1</li>
    <li>item 2</li>
  </ul>
</div>

</body>
</html>
0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜