需要选择第一个孩子

时间:2019-06-26 04:16:56

标签: html css

我只需要将第一个元素居中。 示例:文本“ Ajax”应居中对齐,但文本“ Ajax Help”和Ajax Intro”应保持对齐。我需要为所有li元素实现它。

ul.child-sidebar-menu li.current_page_parent a:first-child {
    position: absolute;
    width: 100%;
    text-align: center;
}
<ul class="child-sidebar-menu">
 <li class="page_item page-item-21 current_page_ancestor current_page_parent has_children">
  <a href="http://localhost/html5beta/javascript/ajax/">Ajax</a>
 <ul class="grandchild-sidebar-menu level-0 children">
  <li class="page_item page-item-104 current_page_item">
   <a href="http://localhost/html5beta/javascript/ajax/ajax-help/" aria-current="page">Ajax help</a></li>
<li class="page_item page-item-54"><a href="http://localhost/html5beta/javascript/ajax/ajax-intro/">Ajax Intro</a></li>
</ul>
</li>
<li class="page_item page-item-16"><a href="http://localhost/html5beta/javascript/angular-js/">Angular JS</a></li>
<li class="page_item page-item-29"><a href="http://localhost/html5beta/javascript/jquery/">Jquery</a></li>
<li class="page_item page-item-31"><a href="http://localhost/html5beta/javascript/jason/">Jason</a></li>
<li class="page_item page-item-37"><a href="http://localhost/html5beta/javascript/react-js/">React JS</a></li>
<li class="page_item page-item-39"><a href="http://localhost/html5beta/javascript/node-js/">Node JS</a></li>
</ul>

1 个答案:

答案 0 :(得分:2)

您正在寻找 child combinator > ,以便仅选择a直接个子元素li.current_page_parent,并且不是孙子。

请注意,在这种情况下,您实际上不需要:first-child伪类。

ul.child-sidebar-menu li.current_page_parent > a {
  position: absolute;
  width: 100%;
  text-align: center;
}
<ul class="child-sidebar-menu">
  <li class="page_item page-item-21 current_page_ancestor current_page_parent has_children">
    <a href="http://localhost/html5beta/javascript/ajax/">Ajax</a>
    <ul class="grandchild-sidebar-menu level-0 children">
      <li class="page_item page-item-104 current_page_item">
        <a href="http://localhost/html5beta/javascript/ajax/ajax-help/" aria-current="page">Ajax help</a></li>
      <li class="page_item page-item-54"><a href="http://localhost/html5beta/javascript/ajax/ajax-intro/">Ajax Intro</a></li>
    </ul>
  </li>
  <li class="page_item page-item-16"><a href="http://localhost/html5beta/javascript/angular-js/">Angular JS</a></li>
  <li class="page_item page-item-29"><a href="http://localhost/html5beta/javascript/jquery/">Jquery</a></li>
  <li class="page_item page-item-31"><a href="http://localhost/html5beta/javascript/jason/">Jason</a></li>
  <li class="page_item page-item-37"><a href="http://localhost/html5beta/javascript/react-js/">React JS</a></li>
  <li class="page_item page-item-39"><a href="http://localhost/html5beta/javascript/node-js/">Node JS</a></li>
</ul>

您的其他<li>元素没有.current_page_parent类,因此如果要定位其{理论上的)子级,则可以定位.page_item > a