CSS :target 选择器
CSS :target 伪类 代表一个唯一的页面元素(目标元素),其id 与当前URL片段匹配 .
实例
突出显示活动的 HTML 锚:
<!DOCTYPE html><html><head><style>:target {border: 2px solid #D4D4D4;background-color: #e5eecc;}</style></head><body><h2>这是一个标题</h2><p><a href="#news1">跳转到新内容 1</a></p><p><a href="#news2">跳转到新内容 2</a></p><p>单击上面的链接,:target 选择器高亮显示当前活动的 HTML 锚文本。</p><p id="news1"><b>新内容 1...</b></p><p id="news2"><b>新内容 2...</b></p></body></html>
浏览器支持
表格中的数字注明了完全支持该选择器的首个浏览器版本。
| 选择器 | |||||
|---|---|---|---|---|---|
| :target | 4.0 | 9.0 | 3.5 | 3.2 | 9.6 |
定义和用法
URL 带有后面跟有锚名称 #,指向文档内某个具体的元素。这个被链接的元素就是目标元素(target element)。
:target 选择器可用于选取当前活动的目标元素。
CSS 语法
:target { css declarations;}
更多实例
创建选项卡式菜单:
<!DOCTYPE html><html><head><style>.tab div {display: none;}.tab div:target {display: block;}</style></head><body><div class="tab"><a href="#link1">Link 1</a><a href="#link2">Link 2</a><a href="#link3">Link 3</a><div id="link1"><h3>Content to Link 1</h3><p>Hello World!</p></div><div id="link2"><h3>Content to Link 2</h3><h4>Great success!</h4></div><div id="link3"><h3>Content to Link 3</h3><p>Yeah!</p></div></div></body></html>
创建模态(对话框):
<!DOCTYPE html><html><head><style>/* Add animation (Chrome, Safari, Opera) */@-webkit-keyframes example {from {top:-100px;opacity: 0;}to {top:0px;opacity:1;}}/* Add animation (Standard syntax) */@keyframes example {from {top:-100px;opacity: 0;}to {top:0px;opacity:1;}}/* The modal's background */.modal {display: none;position: fixed;left: 0;top: 0;width: 100%;height: 100%;overflow: auto;background-color: rgb(0, 0, 0);background-color: rgba(0, 0, 0, 0.4);}/* Display the modal when targeted */.modal:target {display: table;position: absolute;}/* The modal box */.modal-dialog {display: table-cell;vertical-align: middle;}/* The modal's content */.modal-dialog .modal-content {margin: auto;background-color: #f3f3f3;position: relative;padding: 0;outline: 0;border: 1px #777 solid;text-align: justify;width: 80%;box-shadow: 0 4px 8px 0 rgba(0, 0, 0, 0.2), 0 6px 20px 0 rgba(0, 0, 0, 0.19);/* Add animation */-webkit-animation-name: example; /* Chrome, Safari, Opera */-webkit-animation-duration: 0.5s; /* Chrome, Safari, Opera */animation-name: example;animation-duration: 0.5s;}/* The button used to close the modal */.closebtn {text-decoration: none;float: right;font-size: 35px;font-weight: bold;color: #fff;}.closebtn:hover,.closebtn:focus {color: #000;text-decoration: none;cursor: pointer;}.container {padding: 2px 16px;}header {background-color: #5cb85c;font-size: 25px;color: white;}footer {background-color: #5cb85c;font-size: 20px;color: white;}</style></head><body><a href="#id01">Open Modal</a><div id="id01" class="modal"><div class="modal-dialog"><div class="modal-content"><header class="container"><a href="#" class="closebtn">×</a><h2>Modal Header</h2></header><div class="container"><p>Some text in the modal.</p><p>Some text in the modal.</p></div><footer class="container"><p>Modal footer</p></footer></div></div></div></body></html>