纯css实现tab切换你会吗?(锚点定位)

2,833 阅读1分钟

纯css实现tab切换另一种方法(input法):纯css实现tab切换(input[type=radio])

效果

在这里插入图片描述

1、核心

每项【切换内容】的宽高为【内容展示区域】的宽高,【内容展示区域】设置超出部分隐藏,每次锚点定位后,其余【切换内容】部分会被挤出【内容展示区域】并被隐藏,以此达到tab切换效果。

2、注意

该方法,默认状态时tab选项没有激活颜色,如果有人想到方法,希望在评论区指点一下。

3、css代码

   	/* 
         * 整体宽、高均为可视化窗口的一半
         */
        .tab-box {
            width: 50vw;
            height: 50vh;
            margin: 0 auto;
            border: 1px solid #f0f;
            border-radius: 5px;
            overflow: hidden;
        }
        /* ul使用flex布局,使li铺满 */
        .tab-nav {
            width: 100%;
            height: 60px;
            padding: 0;
            margin: 0;
            list-style: none;
            display: flex;
        }
        /* li均分ul宽度,给选项卡统一背景色 */
        .tab-nav li {
            flex: 1;
            height: 60px;
            text-align: center;
            background: cornflowerblue;
        }
        /* 选项卡a撑高 */
        .tab-tit {
            display: block;
            width: 100%;
            height: 100%;
            line-height: 60px;
            cursor: pointer;
            text-decoration: none;
            color: #000;
        }
        /* 
         * hover高亮
		 */
        .tab-tit:hover {
            background: #f0f;
            color: #fff;
        }
        /* 计算内容展示区域高度,超出部分隐藏 */
        .tab-content {
            height: calc(100% - 60px);
            overflow: hidden;
        }
        /* 各项内容宽高为内容展示区域宽高,通过锚点定位 */
        .tab-content div {
            text-align: left;
            height: 100%;
            text-indent: 2em;
            padding: 10px;
            box-sizing: border-box;
        }

4、html代码

     <div class="tab-box">
        <ul class="tab-nav">
            <li><a class="tab-tit" href="#active1">第一项</a></li>
            <li><a class="tab-tit" href="#active2">第二项</a></li>
            <li><a class="tab-tit" href="#active3">第三项</a></li>
            <li><a class="tab-tit" href="#active4">第四项</a></li>
        </ul>
        <div class="tab-content">
            <div class="tab-content" id="active1">内容1</div>
            <div class="tab-content" id="active2">内容2</div>
            <div class="tab-content" id="active3">内容3</div>
            <div class="tab-content" id="active4">内容4</div>
        </div>
    </div>

到这里就实现,如果对你有帮助可以点赞、收藏+关注哦~😘下面是另一种方法
纯css实现tab切换另一种方法(input法):纯css实现tab切换(input[type=radio])