为了在纯 CSS 中工作,需要对 HTML 进行更改(因为 CSS 只能针对出现在 DOM 中较晚的元素(作为后来的兄弟姐妹,或后代,或这两者的组合)而不是它们所在的元素重新设置样式。因此,HTML 现在是:
<p>Here's a list</p>
<div id="top">
<ol id="list">
<li>item 1</li>
<li>item 2</li>
<li>item 3</li>
</ol>
<a href="#top" class="hide">[hide]</a>
<a href="#list" class="show">[show]</a>
</div>
<p>How about that?</p>
另请注意,div
现在有一个id
以便允许隐藏列表(同样,仅使用 CSS 和基本 HTML)。
CSS 有点复杂,但通过以下方式解释/* comments in the CSS itself */
:
.show,
.hide {
/* allows for the links to be positioned 'ahead' of the list
whose appearance they control */
position: absolute;
top: 0.1em;
/* allows for an assigned width, height, etc... */
display: inline-block;
width: 5em;
height: 2em;
line-height: 2em;
text-align: center;
}
.hide {
left: 0;
}
.show {
/* this is why we have an assigned width */
left: 5.1em;
}
#list {
/* hides on page-load */
display: none;
}
#list:target {
/* when clicking the 'show' link the #list is targeted
and is shown */
display: block;
}
#list:target ~ .show {
/* reduces the opacity of the 'show' link, when
the list is already shown */
opacity: 0.3;
}
#list:target ~ .hide {
/* when the list is shown, the 'hide' link is visible */
opacity: 1;
}
#top {
/* allows the links to be positioned visually ahead of,
and relative to, the menu */
position: relative;
/* slightly greater than the defined height of
the link elements */
padding-top: 2.2em;
}
#top .hide,
#top:target .hide {
/* hides the 'hide' link when the list is, itself, hidden */
opacity: 0.3;
}
JS 小提琴演示。
稍作修改(添加了另一个元素来包装链接)版本,以便更轻松地定位它们(而不是在设置left
位置之前手动计算每个链接的宽度):
<p>Here's a list</p>
<div id="top">
<ol id="list">
<li>item 1</li>
<li>item 2</li>
<li>item 3</li>
</ol>
<!-- could use a div, it doesn't matter -->
<span id="controls">
<a href="#top" class="hide">[hide]</a>
<a href="#list" class="show">[show]</a>
</span>
</div>
<p>How about that?</p>
使用 CSS:
#controls {
position: absolute;
top: 0.1em;
left: 0;
height: 2em;
line-height: 2em;
}
.show,
.hide {
display: inline-block;
width: 5em;
text-align: center;
}
#list {
display: none;
}
#top {
position: relative;
padding-top: 2.2em;
}
#list:target {
display: block;
}
#list:target ~ #controls .hide {
opacity: 1;
}
#list:target ~ #controls .show {
opacity: 0.3;
}
#top #controls .hide {
opacity: 0.3;
}
#top:target #controls .hide {
opacity: 0.3;
}
JS 小提琴演示。
或者,改为使用visibility: hidden
/visibility: visible;
。