【问题标题】:Use Flexbox to create a responsive layout使用 Flexbox 创建响应式布局
【发布时间】:2019-08-24 22:29:31
【问题描述】:

这是我第一次尝试使用 Flexbox,但遇到了一些问题。

我想创建一个可在桌面、平板电脑和类似这样的布局上运行的响应式布局:

我写了这段代码:

var screenType = 'mobile' // this variable return 'mobile' or 'tablet' or 'desktop'
.container {
  display: flex;
  flex-wrap: wrap;
  flex-direction: row;
}

.big {
  background-color: tomato;
  width: 60%;
  height: 100%;
}

.small {
  background-color: green;
  width: 40%;
  height: 100%;
}
<div class="container">
  <div class="big">big</div>
  <div class="small">small</div>
</div>

如何使用变量类型来使用 Flex 创建不同的布局?

我想我必须更改widthheightflex-direction 但我不知道如何...

【问题讨论】:

  • "如何使用变量类型来使用 Flex 创建不同的布局?" - 别。请改用媒体查询。
  • @Quentin 你能解释一下吗?

标签: javascript css layout flexbox


【解决方案1】:

如果您有一个填充了预设屏幕类型的 JS 变量,那么您可以将其用作添加到 &lt;body&gt; 元素的类名,例如:

document.body.classList.add(screenType);

然后在您的 CSS 中,您只需创建预先存在的样式的修饰符,例如 .g

.container {
  // Default styles for desktop
}

.mobile .container,
.tablet .container {
  // Modified styles for mobile/tablet
}

除此之外,您还需要在 flexbox 规范中使用 order 属性,以便重新排列元素。

一个专业提示:我强烈建议不要通过外观来命名您的类(bigsmall 等),而是给它们一个语义名称,以便它们与外观分离。在您的示例中,.big 容器在某些设备上很大,但在其他设备上实际上很小。

参见概念验证示例:

function setScreenType() {
  var screenType = document.getElementById('screenType').value;
  document.body.classList.remove('mobile', 'desktop', 'tablet');
  document.body.classList.add(screenType);
}

setScreenType();

document.getElementById('screenType').addEventListener('change', function() {
  setScreenType();
});
body {
  margin: 0;
  padding: 0;
}

.container {
  display: flex;
  flex-wrap: wrap;
  flex-direction: row;
  flex: 1 1 auto;
  width: 100vw;
  height: 100vh;
}

.content1 {
  background-color: tomato;
  width: 80%;
  height: 100%;
  order: 2;
}

.content2 {
  background-color: green;
  width: 20%;
  height: 100%;
  order: 1;
}

.mobile .container,
.tablet .container {
  flex-direction: column;
}

.mobile .content1,
.tablet .content1 {
  width: 100%;
  height: 20%;
  order: 1;
}

.mobile .content2,
.tablet .content2 {
  width: 100%;
  height: 80%;
  order: 2;
}
<!-- This is just to simulate different screen types -->
<form>
  <select id="screenType">
    <option value="mobile" selected>Mobile</option>
    <option value="tablet">Tablet</option>
    <option value="desktop">Desktop</option>
  </select>
</form>

<div class="container">
  <div class="content1">content1</div>
  <div class="content2">content2</div>
</div>

【讨论】:

    猜你喜欢
    • 2022-01-12
    • 2021-06-12
    • 1970-01-01
    • 2019-09-15
    • 2018-03-19
    • 2019-03-12
    • 2018-06-22
    • 1970-01-01
    • 2019-10-13
    相关资源
    最近更新 更多