
💎知识点:
1️⃣ :hover 和 :checked 选择器
2️⃣ transition 过渡属性
3️⃣ input 单选按钮
思路:
创建三个单选按钮并隐藏,然后绘制三个导航栏按钮,再利用单选按钮选中状态来改变导航栏中的按钮样式。
利用单选按钮来模拟导航栏点击选中效果,实现一个简约的文字类导航栏。
核心代码部分,简要说明了写法思路;完整代码在最后,可直接复制到本地运行。
导航栏主体结构html代码:
<nav class="nav92">
<label class="label92">
<input id="sel91-1" class="inp92" type="radio" name="radio92" checked="" />
<span class="nav-a92">首页</span>
</label>
<label class="label92">
<input id="sel91-2" class="inp92" type="radio" name="radio92" />
<span class="nav-a92">设计</span>
</label>
<label class="label92">
<input id="sel91-3" class="inp92" type="radio" name="radio92" />
<span class="nav-a92">前端</span>
</label>
</nav>
css 部分代码:
.nav92{
height: 32px;
padding: 4px;
position: relative;
overflow: hidden;
display: flex;
background-color: #eee;
box-shadow: 010px10px -5pxrgba(0, 0, 0, 0.2);
border-radius: 20px;
}
.label92{
cursor: pointer;
}
.label92.inp92{
display: none;
}
.nav-a92{
width: 88px;
height: 32px;
line-height: 32px;
border-radius: 16px;
display: block;
color: #3d3d3d;
font-size: 14px;
text-decoration: none;
transition: all 0.4s linear;
}
.nav-a92:hover{
font-weight: bold;
}
.inp92:checked + .nav-a92{
font-weight: bold;
background-color: #ffffff;
}
1、先绘制出导航栏整体的一个轮廓以及基本样式,并且隐藏掉单选按钮 display: none;。
2、定义按钮的基本样式以及字体样式,默认给按钮添加透明背景,然后加上 transition 过渡属性。
3、利用 :hover 选择器,当鼠标悬浮在按钮上方时,字体变粗。
4、最后再利用 :checked 选择器,来判断当按钮选中时,给选中的按钮添加背景色。
注意 :checked + [classname] 选择器这样写时,是表示选中按钮的下一个同级元素,要注意 html 的元素结构,否则就不起作用。
完整代码如下,html 页面:
<!DOCTYPE html>
<html lang="zh">
<head>
<meta charset="utf-8">
<link rel="stylesheet" href="style.css">
<title>92 简约文字风格导航栏</title>
</head>
<body>
<div class="app">
<nav class="nav92">
<label class="label92">
<input id="sel91-1" class="inp92" type="radio" name="radio92" checked="" />
<span class="nav-a92">首页</span>
</label>
<label class="label92">
<input id="sel91-2" class="inp92" type="radio" name="radio92" />
<span class="nav-a92">设计</span>
</label>
<label class="label92">
<input id="sel91-3" class="inp92" type="radio" name="radio92" />
<span class="nav-a92">前端</span>
</label>
</nav>
</div>
</body>
</html>
完整代码如下,css 样式:
/** style.css **/
.app{
width: 100%;
height: 100vh;
background-color: #fff;
position: relative;
display: flex;
justify-content: center;
align-items: center;
}
.nav92{
height: 32px;
padding: 4px;
position: relative;
overflow: hidden;
display: flex;
background-color: #eee;
box-shadow: 010px10px -5pxrgba(0, 0, 0, 0.2);
border-radius: 20px;
}
.label92{
cursor: pointer;
}
.label92.inp92{
display: none;
}
.nav-a92{
width: 88px;
height: 32px;
line-height: 32px;
border-radius: 16px;
background-color: transparent;
text-align: center;
display: block;
color: #3d3d3d;
font-size: 14px;
text-decoration: none;
transition: all 0.4s linear;
}
.nav-a92:hover{
font-weight: bold;
}
.inp92:checked + .nav-a92{
font-weight: bold;
background-color: #ffffff;
}

转载作品,原作者:设计师工作日常,文章来源:https://mp.weixin.qq.com/s/jDhwWVIs9qDgDCOyKm8MGg