【发布时间】:2022-01-21 16:52:12
【问题描述】:
我想在大屏幕的两个元素之间夹入一个垂直布局(示例 2)——对于小屏幕,让最左边和最里面的元素彼此相邻,然后是下面的所有其他元素它(示例 3)。
但我试图避免编写两种不同的 HTML 结构,这是我目前可以实现的唯一方法。我想知道我是否可以使用 flexbox 做到这一点。
(function(){
const toggle_butt = document.querySelector('[name="mobile"]');
const root_el = document.querySelector('.root');
if (!toggle_butt || !root_el) {
return false;
}
toggle_butt.onchange = () => {
if (root_el.classList.contains('mobile')) {
root_el.classList.remove('mobile');
} else {
root_el.classList.add('mobile');
}
};
})()
.root {
max-width: 600px;
border: 1px dashed gray;
padding: 0.25rem;
}
.root.mobile {
max-width: 320px;
}
.controller {
margin-bottom: 0.5rem;
}
[class*="example-"] + [class*="example-"] {
margin-top: 1rem;
}
.d-flex {
display: flex;
flex-wrap: wrap;
}
.red, .yellow, .green, .blue {
min-width: 50px;
min-height: 40px;
}
.red {
background-color: tomato;
}
.yellow {
background-color: gold;
height: 40px;
}
.green {
background-color: limegreen;
height: 50px;
}
.blue {
background-color: cornflowerblue;
}
/* ----------- */
.example-1 .red {
flex: 0 0 20%;
}
.example-1 .yellow {
flex: 1 0 70%;
}
.example-1 .green {
flex: 0 0 100%;
}
.example-1 .blue {
flex: 0 0 100px;
}
.root.mobile .example-1 .blue {
flex: 1 0 100%;
}
/* ----------- */
.example-2 .red {
flex: 0 0 20%;
}
.example-2 .yellow,
.example-2 .green {}
.example-2 .blue {
flex: 0 0 100px;
}
.example-2 .cheat {
flex: 1 0 50%;
}
/* ----------- */
.example-3 .red {
flex: 0 0 20%;
}
.example-3 .yellow {
flex: 1 0 70%;
}
.example-3 .green,
.example-3 .blue {
flex: 1 0 100%;
}
.example-3 .cheat {
display: flex;
flex: 1 0 100%;
}
<div class="root">
<div class="controller">
<label>
<input type="checkbox" name="mobile" />
<span class="text">mobile</span>
</label>
</div>
<div class="example-1 d-flex">
<div class="red"></div>
<div class="yellow">Can flex do it?</div>
<div class="green"></div>
<div class="blue"></div>
</div>
<div class="example-2 d-flex">
<div class="red"></div>
<div class="cheat">
<div class="yellow">Goal: desktop</div>
<div class="green"></div>
</div>
<div class="blue"></div>
</div>
<div class="example-3 d-flex">
<div class="cheat">
<div class="red"></div>
<div class="yellow">Goal: mobile</div>
</div>
<div class="green"></div>
<div class="blue"></div>
</div>
</div>
绿色与红色和蓝色的底边对齐并不重要。
红色是图片,黄色是标题;这就是我尝试这样做的原因。
我看过的 StackOverflow 问题(但它们并不完全相同):
【问题讨论】: