什么是CSS伪类?
通常选择器不能表现HTML元素或属性的状态,我们可以在CSS选择器上添加伪类表示元素的状态、特征。伪类名写在选择器的:冒号后面,必要时可以添加()
,例如:#comments:not(:target)
。
:target
伪类用来指定那些包含片段标识符的 URL 的目标元素样式。 例如:http://www.css88.com/demo/target-selector/#target-test这个 URL 包含了#target-test 片段标识符
。 在HTML中, 标识符是元素的id(或者name属性)。 这个示例 URL 指向的是ID为”target-test”的元素 。看看这个最简单的例子,页面上有个元素,如下:
html 代码:
<div id="target-test">这个元素的id为"target-test"</div>
添加CSS代码:
css 代码:
#target-test {
background-color: transparent;
border-bottom: 3px solid #ffdb3a;
font-weight: 700;
}
#target-test:target {
background-color: #ffdb3a;
}
点击查看:http://www.css88.com/demo/target-selector/
当然这个是最简单的例子,下面我介绍几个有意思的例子。(例子来自:https://github.com/ireade/demo.bitsofco.de)
例子1:显示/隐藏评论
不用任何javaScript实现显示/隐藏评论效果
主要的html代码:
html 代码:
<a href="#comments">Show Comments</a>
<section id="comments">
<h3>Comments</h3>
<!-- Comments here... -->
<a href="#">Hide Comments</a>
</section>
主要的CSS代码:
js 代码:
#comments:not(:target) {
display: none;
}
#comments:target {
display: block;
}
具体效果查看:http://www.css88.com/demo/target-selector/hide-show.html
例子2:显示/隐藏屏幕侧边栏
这个比较常见,比较实用,技巧点:边栏高度自适应屏幕(100%),并且固定定位(position: fixed;)。
主要的CSS代码:
css 代码:
#nav {
position: fixed;
top: 0;
height: 100%;
width: 80%;
max-width: 400px;
}
#nav:not(:target) {
right: -100%;
transition: right 1.5s;
}
#nav:target {
right: 0;
transition: right 1s;
}
具体效果查看:http://www.css88.com/demo/target-selector/slide-out.html
例子3:显示/隐藏模态框
还有填充屏幕的半透明遮罩层哦
主要的CSS代码:
css 代码:
#modal-container {
position: fixed;
top: 0;
left: 0;
width: 100%;
height: 100%;
background: rgba(0,0,0,0.8);
display: flex;
justify-content: center;
align-items: center;
}
.modal {
width: 70%;
background: #fff;
padding: 20px;
text-align: center;
}
#modal-container:not(:target) {
opacity: 0;
visibility: hidden;
transition: opacity 1s, visibility 1s;
}
#modal-container:target {
opacity: 1;
visibility: visible;
transition: opacity 1s, visibility 1s;
}
具体效果查看:http://www.css88.com/demo/target-selector/modal.html
例子4:显示/隐藏边栏
主要的CSS代码:
css 代码:
#body:not(:target) {
main { width: 60%; }
aside { width: 30%; }
.show-sidebar-link { display: none; }
}
#body:target {
main { width: 100%; }
aside { display: none; }
.hide-sidebar-link { display: none; }
}
具体效果查看:http://www.css88.com/demo/target-selector/body.html
实际应用中存在的问题
锚点链接会使页面跳到目标元素的位置,造成用户体验上的不爽;
浏览器前进、后退时候会反复应用:target 伪类效果
关注WEB前端开发官方公众号
关注国内外最新最好的前端开发技术干货,获取最新前端开发资讯,致力于打造高质量的前端技术分享公众号
版权声明
本文仅用于学习、研究和交流目的,欢迎非商业性质转载。
转载请注明文章的完整链接:http://www.css88.com/archives/6256
作者(译者): 愚人码头 及 网站出处:CSS88.com