Show section/div depends on after hash # value in link

问题: I have following page section { height: 1000px; background: yellow; margin: 50px; } <section id="one">Section one</section> <section...

问题:

I have following page

section {
 height: 1000px;
 background: yellow;
 margin: 50px;
}
<section id="one">Section one</section>
<section id="two">Section two</section>

It is possible using html/css only to show only ONE section if user came from link which contains section id after hash e.g

?


回答1:

My solution contains no HTML nesting and scales easily. It uses :target and general sibling combinator to find matches and show only the targeted section.

 /* Display all sections initially */
section {
 height: 1000px;
 background: yellow;
 margin: 50px;
}

/* Hide all targeted sections initially */
span:target ~ section {
  display: none;
}
 
/* Display only the targeted section */
span:nth-of-type(1):target ~ section:nth-of-type(1),
span:nth-of-type(2):target ~ section:nth-of-type(2),
span:nth-of-type(3):target ~ section:nth-of-type(3),
span:nth-of-type(4):target ~ section:nth-of-type(4),
span:nth-of-type(5):target ~ section:nth-of-type(5) {
  display: block;
}
<a href="#one">one</a>
<a href="#two">two</a>
<a href="#three">three</a>
<a href="#four">four</a>
<a href="#five">five</a>
<!-- <a href="#n">n</a> -->

<span id="one"></span>
<span id="two"></span>
<span id="three"></span>
<span id="four"></span>
<span id="five"></span>
<!-- <span id="n"></span> -->

<section>Section one</section>
<section>Section two</section>
<section>Section three</section>
<section>Section four</section>
<section>Section five</section>
<!-- <section>Section n</section> -->


回答2:

You can investigate the use of the :target pseudo-class, but you might struggle to show all of the sections when the URL hash is empty.

For example:

section:not(:target) { display:none; }
section:target { display: block }
<a href="#one">One</a>
<a href="#two">Two</a>

<section id="one">Section one</section>
<section id="two">Section two</section>


回答3:

Probably JavaScript is the best way to go about this, but if you really don't want to use it, you can use the :target approach suggested by BenM in combination with duplicated HTML.

When there is no :target, you show the duplicated HTML. When there is a target, you show the target and hide everything else.

Like this:

#one,
#two {
  display: none;
}
#one:target,
#two:target {
  display: block;
}
#one:target ~ div,
#two:target ~ div {
  display: none;
}
<a href="#one">one</a>
<a href="#two">two</a>

<div id="one">Section one</div>
<div id="two">Section two</div>
<div id="one-duplicate">Section one</div>
<div id="two-duplicate">Section two</div>

  • 发表于 2019-02-14 19:35
  • 阅读 ( 236 )
  • 分类:网络文章

条评论

请先 登录 后评论
不写代码的码农
小编

篇文章

作家榜 »

  1. 小编 文章
返回顶部
部分文章转自于网络,若有侵权请联系我们删除