很多人做tab选项卡会用到js,通过排他思想去实现选项卡,其实只用css也可以轻松实现。
效果如下
html代码如下
<div class="tab">
<input type="radio" name="tab-one" id="r1" class="hid" checked />
<input type="radio" name="tab-one" id="r2" class="hid" />
<input type="radio" name="tab-one" id="r3" class="hid" />
<ul class="label-list">
<li>
<label for="r1">选项卡1</label>
</li>
<li>
<label for="r2">选项卡2</label>
</li>
<li>
<label for="r3">选项卡3</label>
</li>
</ul>
<div class="box-one">1</div>
<div class="box-two">2</div>
<div class="box-three">3</div>
</div>
css
<style>
*{
padding: 0px;
margin: 0px;
}
body{
background-color: #fff;
}
.tab{
background-color: antiquewhite;
width: 500px;
height: 300px;
position: absolute;
top: 0px;
bottom: 0px;
left: 0px;
right: 0px;
margin: auto;
}
.box-one,
.box-two,
.box-three{
width: 100%;
height: 85%;
display: none;
}
#r1:checked ~ .box-one{
display: block;
}
#r1:checked ~ .label-list>li label[for="r1"]{
color: blueviolet;
background-color: antiquewhite;
}
#r2:checked ~ .box-two{
display: block;
}
#r2:checked ~ .label-list>li label[for="r2"]{
color: blueviolet;
background-color: antiquewhite;
}
#r3:checked ~ .box-three{
display: block;
}
#r3:checked ~ .label-list>li label[for="r3"]{
color: blueviolet;
background-color: antiquewhite;
}
.label-list{
display: flex;
background-color: #63ff40;
height: 15%;
}
.label-list li{
list-style-type: none;
}
.label-list li label{
height: 100%;
display: inline-block;
display: flex;
align-items: center;
padding: 0px 10px;
cursor: pointer;
}
.hid{
display: none;
}
</style>
使用html+css实现tab选项卡,我们会用到单选框,一组单选框的每一个选项对应一个卡片。当单选框被选中时,对应的卡片就显示。
这里我们会用到一个css选择器,相邻选择器,也就是哪个波浪线(~),相邻选择器可以选择同级元素。
#r1:checked ~ .box-one{
display: block;
}