前端开发 大前端 W3Cbest

一个专注 WEB 开发的技术博客

0%

使用CSS3 选择器:target制作一个可伸缩的导航菜单

我们使用CSS3 选择器:target制作一个可伸缩的导航菜单。先理解一下:target

定义和用法

URL 带有后面跟有锚名称 #,指向文档内某个具体的元素。这个被链接的元素就是目标元素(target element)。 :target 选择器可用于选取当前活动的目标元素。 那么我就看一下代码如何做可伸缩的导航菜单

CSS代码

nav {
font-size: 12px;
background-color: rgb(19, 51, 61);
box-shadow: 0 1px 2px rgba(19, 51, 61, 0.5);
margin: 3em 0 6em;
padding: 0 1em;
height: 44px;
overflow: hidden;
}

nav ul {
margin: 0;
padding: 0;
list-style-type: none;
max-height: 88px;
position: relative;
}

nav li {
display: inline-block;
}

nav a {
display: inline-block;
padding: 0 1em;
color: rgb(236, 236, 236);
font-weight: 700;
letter-spacing: 0.1em;
text-decoration: none;
text-transform: uppercase;
white-space: nowrap;
line-height: 44px;
height: 44px;
}

nav a:hover {
background-color: rgba(255, 255, 255, 0.08);
}

nav li:last-child {
/* 菜单按钮 */
position: absolute;
right: 0;
bottom: 44px;
background-image: linear-gradient(to right, rgba(19, 51, 61, 0) 0, rgba(19, 51, 61, 1) 2em);
padding-left: 3em;
}

nav li:nth-last-child(2) {
/* 先关闭按钮 */
display: none;
}

nav#menu:target {
height: auto;
padding: 0;
}

nav#menu:target ul {
max-height: none;
}

nav#menu:target li {
display: block;
}

nav#menu:target a {
display: block;
padding: 0 2em;
background-color: rgba(255, 255, 255, 0.05);
}

nav#menu:target a:hover {
background-color: rgba(255, 255, 255, 0.08);
}

nav#menu:target li:not(:first-child) {
margin-top: 2px;
}

nav#menu:target li:last-child {
display: none;
}

nav#menu:target li:nth-last-child(2) {
display: inline-block;
position: absolute;
top: 0;
right: 0;
margin: 0;
border-left: 2px solid rgb(19, 51, 61);
}

查看demo

坚持技术创作分享,您的支持将鼓励我继续创作!