【问题标题】::nth-child not working on anchor tags:nth-child 不处理锚标签
【发布时间】:2017-04-19 08:32:53
【问题描述】:

我正在尝试设计一个带有页眉、侧边栏、页脚和内容部分的页面模板。一切都是固定的,除了内容部分在溢出时滚动。

标题包含一个基本导航栏,其中包含一个无序列表、四个列表项和四个链接到正常“主页”“内容”“关于”“联系人”页面的锚标记。

每个链接都需要一个右边框,最后一个(第 4 个)除外。它们只是为了在视觉上将每一个分开。

代码如下:

#top-nav {
  background-color: orange;
  height: 68px;
  margin: 0;
  padding: 0;
}

#top-nav ul {
  font-size: 0;
  margin: 0;
  padding: 0;
}

#top-nav li {
  list-style-type: none;
  text-align: center;
  height:68px; /*100%, border     doesn't span full height*/
  margin: 0;
  border-right: 1px solid black;
  padding: 23.5px 95px;
  display: inline-block;
}

#top-nav li:nth-child(4) {
  border-right: none;
}

#top-nav a {
  text-decoration: none;
  color: black;
  height: 100%;
  margin: 0;
  padding: 0;
  font-size: 16px;
  display: block;
}
<!--		<PAGE HEADER>		-->
<div id="header">
  <header>

    <!--		<HEADER TITLE>		-->
    <div id="header-title">
      <h1>Page Header</h1>
    </div>
    <!--		</HEADER TITLE>		-->

    <!--		<HEADER NAVBAR>		-->
    <div id="top-nav">
      <ul>
        <li><a href="#">Home</a></li>
        <li><a href="#">Content</a> </li>
        <li><a href="#">About</a> </li>
        <li><a href="#">Contact</a> </li>
      </ul>
    </div>
    <!--		</HEADER NAVBAR		-->

  </header>
</div>
<!--		</HEADER>			-->

此代码按预期工作。

我想要做的是将样式方面移动到锚标记。

当我将样式转移到锚标记并将 nth-child 更改为 a 而不是 li 时,它不起作用。

我也尝试过:last-child,但结果相同,对 li 有效,对 a 无效。

编辑:

这是 CSS:

#top-nav {
    background-color:orange;
    height:68px;
    margin:0;
    padding:0;
} 

#top-nav ul {
    font-size:0;
    margin:0;
    padding:0;
} 

#top-nav li {
    list-style-type:none;
    text-align:center;
    height:68px; /*100%, border     doesn't span full height*/
    margin:0;
/*  border-right:1px solid black;*/
/*  padding:23.5px 95px;*/
display:inline-block;
} 

#top-nav a {
    text-decoration:none;
    color:black;
    height:100%;
    margin:0;
    border-right:1px solid black;
    padding:23.5px 95px;
    font-size:16px;
    display:block;


#top-nav a:nth-child(4) {
    border-right:none;
}

任何帮助将不胜感激。

【问题讨论】:

  • 嗯,我的意思是...li 元素有多少个孩子? a 在什么位置?因为据我所见,所有a 元素都是:nth-child(1)...
  • 你想设计a里面的li对吧?
  • 只是一个提示:最好发布不起作用的代码,而不是有效的代码..
  • @NiettheDarkAbsol 如果我为 li 元素设置右边框,然后使用 #top-nav li:nth-child(4) {border-right:none;} 它会从第四个列表项。我假设第四个 li 将是 ul 的第四个孩子,但我想它不会那样工作?
  • @Tesseract 是的,没错。我希望 li 包含锚点,但仅此而已。

标签: html css


【解决方案1】:

我认为将a 选择器添加到已经适合您的规则中就足够了:

#top-nav li:nth-child(4) a{
  border-right: none;
}

nth-child 选择器适用于兄弟标签,因此在li 标签上使用它是正确的。添加a 选择器,就是说要设置第4 个li 中包含的a 标记的样式。

CSS 样式应用于最后一个选择器。以前的作为上下文(或容器)工作。

【讨论】:

  • 这很好用,谢谢!你能解释一下为什么这种方法有效吗?
  • 在答案中添加了简要说明。
  • 说的有道理,但是为什么在li上可以正常工作,而a却要通过li访问呢?
  • 它不能直接在a上工作,因为a标签不是兄弟:“兄弟元素必须有相同的父元素,adjacent表示立即关注" (source)。
猜你喜欢
  • 1970-01-01
  • 2013-01-22
  • 2013-04-04
  • 1970-01-01
  • 2021-12-14
  • 2012-03-07
  • 1970-01-01
  • 2018-07-30
  • 1970-01-01
相关资源
最近更新 更多