【问题标题】:Re-arranging flex items for mobile and desktop view, without changing the HTML重新排列移动和桌面视图的弹性项目,而不更改 HTML
【发布时间】:2016-04-13 12:16:44
【问题描述】:

我正在为我的网页使用 Angular Material。我必须以不同的方式为桌面和移动设备显示相同的布局。下面是布局和相应的代码:

移动版式 移动代码

<div layout="column" style="text-align: center;">
    <div flex-order="0">
        <div class="child-1">Child 1</div>
    </div>
    <div flex-order="1">
        <div class="child-2">Child 2</div>
    </div>
    <div flex-order="2">
        <div class="child-3">Child 3</div>
    </div>
</div>

桌面布局 桌面代码

<div layout="row" style="text-align: center;">
    <div flex-order="0">
        <div class="child-2">Child 2</div>
    </div>
    <div flex>
        <div layout="column">
            <div flex-order="0">
                <div class="child-1">Child 1</div>
            </div>
            <div flex-order="1">
                <div class="child-3">Child 3</div>
            </div>
        </div>
    </div>
</div>

CSS 代码

.child-1, .child-2, .child-3 {
    border: 1px solid black; 
    background-color: gray; 
    margin-bottom: 10px;
}
.child-1, .child-3 {
    height: 20px;
}
.child-2 {
    height: 40px;
}

有一个明显的 HTML 代码重复来显示不同的布局。有什么方法可以在不复制代码的情况下显示这两种布局?

【问题讨论】:

  • 看看这里发布的替代我的答案:stackoverflow.com/q/34069504/3597276
  • 感谢您指出答案。虽然,我认为它不适用于具有不同浏览器和屏幕方向的所有情况(例如,我需要为孩子 1 和孩子 3 设置不同的高度)。复制代码可能只是一种必要的邪恶。
  • 是否已知任何桌面宽度,特别是 Child2?
  • 好吧,如果您不反对绝对定位,那么仍然可以使用一个版本的 HTML。看我的回答。
  • 如果桌面宽度已知,这很简单。

标签: html css flexbox angular-material


【解决方案1】:

试试这个

   <div layout-sm="column" layout-gt-sm="row">
      <div hide-sm hide-xs style="background:grey" layout-margin> Child 2</div>
      <div layout="column" layout-align="space-around">
          <div  style="background:grey" layout-margin> Child 1</div>
          <div hide-gt-sm style="background:grey"layout-margin > Child 2</div>
          <div  style="background:grey" layout-margin> Child 3</div>
      </div>
   </div>

代码笔here

【讨论】:

    【解决方案2】:

    这是一个干净的解决方案,使用简单的 html 结构,移动设备和桌面设备都相同,并使用媒体查询在更大的屏幕上重新定位 child2

    .parent {
      display: flex;
      flex-flow: column;
      position: relative;
    }
    
    .child1, .child2, .child3 {
        border: 1px solid black; 
        background-color: gray; 
        margin-bottom: 10px;
        height: 20px;
    }
    .child2 {
        height: 40px;
    }
    
    @media screen and ( min-width: 500px) {
      .child2 {
        position: absolute;
        top: 0;
        left: 0;
        height: 52px;
        width: 150px
      }
      .child1,
      .child3 {
        margin-left: 150px;
      }
    }
    <div class="parent">
      <div class="child1">Child 1</div>
      <div class="child2">Child 2</div>
      <div class="child3">Child 3</div>  
    </div>

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2017-04-28
      • 2015-08-05
      相关资源
      最近更新 更多