Search code examples
htmlcsstarget

Having trouble to select an element while other is in :target


i'm just starting to learn how to use html5 and css3, and I came across with this problem:

Is there a way to select other element while other is on :taget with css?

Let me explain with an example:

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>

The idea is to put #menu on target and make #one, for example, change it's color. I had read about "siblings selectors" (+ and ~ i think) is that a possible solution if both elements are sons of the body?

Sorry for my english, it's not my native lenguage. Thanks in advance!


Solution

  • First of all validate your HTML code

    1. there is no </ul> close tag.

    2. </a> tag no need in <li> tag.

    <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>
    

    How can use :target.

    The :target CSS pseudo-class represents a unique element (the target element) with an id matching the URL's fragment.

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

    For example, the following URL has a fragment (denoted by the # sign) that points to an element called section2:

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

    The following element would be selected by a :target selector when the current URL is equal to the above:

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

    Working Demo

    :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>