纯CSS实现tab(:target伪类实现)

By | 2022-03-25

html

<div class="container">
        <div id="content1" class="active">列表1内容:123456</div>
        <div id="content2">列表2内容:abcdefgkijkl</div>
        <ul class='nav'>
            <li class="active"><a href="#content1">列表1</a></li>
            <li><a href="#content2">列表2</a></li>
        </ul>
        <div class="wrap"></div>
</div>

CSS

.container {
    position: relative;
    width: 400px;
    margin: 50px auto;
}
.nav {
    position: relative;
    overflow: hidden;
}
li {
    width: 200px;
    float: left;
    text-align: center;
    background: #ddd;
}
li a {
    display: block;
    width: 200px;
    line-height: 36px;
    font-size: 18px;
    cursor: pointer;
    text-decoration: none;
    color: #000;
}
#content1,
#content2 {
    position: absolute;
    overflow: hidden;
    top: 36px;
    width: 400px;
    height: 100px;
    border: 1px solid #999;
    box-sizing: border-box;
    padding: 10px;
}
#content1,
#content2 {
    display: none;
    width: 100%;
    background: #fff;
}
#content1:target,
#content2:target {
    display: block;
}
#content1.active {
    display: block;
}
.active ~ .nav li {
    &:first-child {
        background: #ff7300;
        color: #fff;
    }
}
#content1:target ~ .nav li {
    background: #ddd;
    color: #000;
    // 改变li元素的背景色和字体颜色
    &:first-child {
        background: #ff7300;
        color: #fff;
    }
}
#content2:target ~ .nav li {
    background: #ddd;
    color: #000;
    // 改变li元素的背景色和字体颜色
    &:last-child {
        background: #ff7300;
        color: #fff;
    }
}
.wrap {
    position: absolute;
    overflow: hidden;
    top: 36px;
    width: 400px;
    height: 100px;
    border: 1px solid #999;
    box-sizing: border-box;
}