CSS direct descendent selectors

人走茶凉 提交于 2021-01-29 18:21:00

问题


I'm having a little trouble and I'm sure there's a simple fix for this seemly trvial question.

I have my HTML page setup with like the follow:

<ul class="locations">
   <li>
      Georgia
      <ul class="children">
         <li>
            Fulton County
            <ul class="children">
               <li>
                  Atlanta
               </li>
            </ul>
         </li>
      </ul>
   </li>
</ul>

I'm trying to style the "parents" list items one way, the "children" one way, and the "grandchildren" another way.

I've tried the following:

ul li{
    list-style: none;
    margin: 0;
}
ul.locations li+ul.children li{
    margin-left: 15px;
    clear: both;
}
ul.locationsli+ul.children li+ul.children li{
    float: left;
}

Where I want the "grandchildren" in this instance to float next to each other...regardless of how I work this our, clear:both; seems to be applied to both the "children" and "grandchildren" items. I also tried using > as a CSS selector with no luck.

Any ideas on fixing this? TIA


回答1:


You're confusing siblings (~ or +) with direct descendants (>). Try this:

jsFiddle

ul li{
    list-style: none;
    margin: 0;
}
ul.locations > li > ul.children > li{
    margin-left: 15px;
    clear: both;
}
ul.locations > li > ul.children  > li > ul.children > li{
    float: left;
}



回答2:


Your example doesn't have any siblings at all, but from what you're describing you don't even want to use sibling selectors (siblings are elements on the same level in the hierarchy). Essentially what you have will work if you remove all the +s, but you also need clear: none on the grandchildren.

ul li{
    list-style: none;
    margin: 0;
}
ul.locations li ul.children li{
    margin-left: 15px;
    clear: both;
}
ul.locations li ul.children li ul.children li {
    float: left;
    clear: none;
}

http://jsfiddle.net/pT8LA/



来源:https://stackoverflow.com/questions/15776379/css-direct-descendent-selectors

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!