前几天想写个Tab导航栏,在搜索引擎搜到C站一位bz的文章(注1)。代码虽短小,觉得有些意思,稍微修葺完成一个简单的Tab导航栏。基本原理是使用radio类型的input标签的属性选择器来修改不同状态tab标签的style样式和内容模块的z-index属性,从而实现tab标签的状态转换和内容显示。不得不说,CSS选择器2真的很强大。适当的使用就可以精简很多不必要的代码。当然配合使用Javascript提升用户体验也是不错的选择。为了简化说明,这里没有提及Javascript代码。实际应用中,是有必要使用Javascript来实时更新页面的。
DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>MyFintitle>
head>
<style type="text/css">
.tabs{
position: relative;
/** note 1 **/
height: 1918px;
/** just for test **/
min-height: 1920px;
max-height: 1920px;
clear: both;
margin: 25px 0;
/** note 2 **/
overflow:scroll;
}
.tab{
float: left;
margin: 25px 0;
}
.tab [type=radio]{
display: none;
}
.tab label{
background: #eee;
padding: 10px 20px;
position: relative;
left: 1px;
border: 0px solid #ccc;
margin-left: -1px;
/** note 3 **/
z-index: 2;
color: #333333;
background: white;
}
.content{
position: absolute;
/** note4 **/
top: 61px;
left: 0;
right: 0;
bottom: 0;
background: white;
padding: 20px 20px;
border: 0px solid #ccc;
}
[type=radio]:checked ~ label{
color: white;
background: #3288e9;
border: 0px solid #ccc;
/** note 5 **/
z-index: 3;
}
[type=radio]:checked ~ label ~ .content{
/** note 6 **/
z-index: 1;
}
/**
.uploads{
list-style: none;
margin: 0 auto;
padding: 0;
}
.uploads img{
max-with: 100%;
max-height: 420px;
display: block;
margin: 0 auto;
}
.uploads li{
margin: 0 auto;
max-width: 25%;
overflow:hidden;
float: left;
}
.uploads li .title{
padding: 5px;
margin: 0 auto;
display: block;
max-width: 100%;
text-align: center;
float: left;
overflow: hidden;
text-overflow: hidden;
}**/
style>
<body>
<div class="tabs">
<div class="tab">
<input type="radio" id="tab1" name="group-1" checked>
<label for="tab1">Indexlabel>
<div class="content">Welcome!div>
div>
<div class="tab">
<input type="radio" id="tab2" name="group-1">
<label for="tab2">Newslabel>
<div class="content">Recent newsdiv>
div>
<div class="tab">
<input type="radio" id="tab3" name="group-1">
<label for="tab3">Photoslabel>
<div class="content">Photo gallerydiv>
div>
<div class="tab">
<input type="radio" id="tab4" name="group-1">
<label for="tab4">Movieslabel>
<div class="content">Hot moviesdiv>
div>
<div class="tab">
<input type="radio" id="tab5" name="group-1">
<label for="tab5">Uploadslabel>
<div class="content">
Uploaded files
div>
div>
div>
body>
html>

统一固定Tab标签页面最大高度,是为了防止一些长页面拼接式出现在短页面下面。
overflow属性设置为scroll,完整展示超出note 1的固定高度的长页面。
note 3 、note 5和note 6中z-index分别设置不同的值,突出显示活跃状态tab标签,且防止由于叠加影响彼此的style样式。
略
参考案例代码——听我一言:Html+CSS:Tab页实现 ↩︎