Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
2.5k views
in Technique[技术] by (71.8m points)

用纯css怎么实现A元素+B元素,A是绿色背景,A元素+C元素,A是红色背景?

<div class="A"></div> // 期待这个样式是绿色背景
<div class="B"></div>

<div class="A"></div>// 期待这个样式是红色背景
<div class="C"></div>


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

给一个思路:
这个需求可以实现,但是首先说明一点是CSS中,不能用后面的元素来约束前面元素的样式,仅能用前面元素约束后面元素的样式。
实现方案为使用flex,DOM结构上让A在BC后面,但是使用order属性调换位置。
效果:
image.png

<div class="container">
    <div class="B">B</div>
    <div class="A">A</div>
</div>

<div class="container">
    <div class="C">C</div>
    <div class="A">A</div>
</div>
.A, .B, .C {
    width: 100px;
}

.A {
    height: 100px;
    order: 1
}

.B, .C {
    background: grey;
    height: 20px;
    order: 2
}

.C + .A {
    background: red;
}

.B + .A {
    background: green;
}

.container {
    display: flex;
    flex-direction: column;
    margin: 10px;
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...