:other不在时,无法选择元素

问题描述

我才刚刚开始学习如何使用html5和css3,我遇到了这个问题:

当其他元素在CSS上的:taget上时,是否可以选择其他元素?

让我举例说明:

Html:
<body>
<header>
<nav id="menu">
    <ul id="buttons">
       <li><a href="#">button</a></li>
       <li><a href="#">button</a></li>
    </ul>
</nav>
</header>

<section id="one">
   <h2>title</h2>
   <p>text</p>
<section>
</body>

这个想法是将#menu放在目标上并设置为#one,例如,更改其颜色。 我读过有关“兄弟姐妹选择器”的信息(我认为+和〜是这样),如果这两个元素都是身体的儿子,那么可能的解决方案吗?

对不起,我的英语不是我的母语。预先感谢!

解决方法

首先验证您的HTML代码

  1. 没有</ul>关闭标签。

  2. </a>标签不需要<li>标签。

<body>
    <header>
    <nav id="menu">
        <ul id="buttons">
           <li>text</li>
           <li>text</li>
        </ul>
    </nav>
    </header>
    
    <section id="one">
       <h2>title</h2>
       <p>text</p>
    <section>
</body>

如何使用:target

:target CSS伪类表示一个唯一元素(目标元素),其ID与URL的片段匹配。

/* Selects an element with an ID matching the current URL's fragment */
:target {
  border: 2px solid black;
}

例如,以下URL包含一个片段(以#号表示),该片段指向名为section2的元素:

http://www.example.com/index.html#section2

当当前URL等于上述URL时,:target选择器将选择以下元素:

<section id="section2">Example</section>

工作演示

:target {
  color: #00cc00;
}
<h3>Table of Contents</h3>
<ol>
 <li><a href="#p1">Jump to the first paragraph!</a></li>
 <li><a href="#p2">Jump to the second paragraph!</a></li>
 <li><a href="#nowhere">This link goes nowhere,because the target doesn't exist.</a></li>
</ol>

<h3>My Fun Article</h3>
<p id="p1">You can target <i>this paragraph</i> using a
  URL fragment. Click on the link above to try out!</p>
<p id="p2">This is <i>another paragraph</i>,also accessible
  from the links above. Isn't that delightful?</p>