弹性布局小技巧分享

157 阅读1分钟

工作中特别常见的设计稿,如下:

我首选布局方案,弹性布局,直接贴码:

html

  <div class="container">
    <div class="left">1</div>
    <div class="right">我是一段描述我是一段描述我是一段描述</div>
  </div>

css

    .container {
        /* 这里宽度先写死 */
        width: 200px;
        height: 50px;
        padding: 0 10px;
        border: 1px solid #ccc;
        display: flex;
        /* 垂直方向居中 */
        align-items: center;
    }

    .left {
        width: 20px;
        height: 20px;
        /* 宽度不被挤压 */
        flex-shrink: 0;
        background: #00DEFF;
        line-height: 20px;
        text-align: center;
        margin-right: 10px;;
        color: #fff;
    }

    .right {
        /* 占据剩余空间 */
        width: 100%;
    }

布局关键在于这行代码:flex-shrink:0 ,如果没有这行,左侧小方块将会被挤压变形。当然不嫌麻烦的话,你也可以手动计算.right的宽度。

结束,拜拜。