使用Flexbox创建响应式布局

时间:2019-04-03 11:45:19

标签: javascript css3 layout flexbox

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

我想创建一种适用于台式机,平板电脑和此类布局的自适应布局:

layout

我写这段代码:

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,但是我不知道如何...

1 个答案:

答案 0 :(得分:0)

如果您有一个使用预设屏幕类型填充的JS变量,则可以将其用作添加到<body>元素的类名,例如:

document.body.classList.add(screenType);

然后在CSS中,您只需创建您现有样式的修饰符即可,例如

.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>