【问题标题】:Display flex, align a div in the bottom right corner of its container显示 flex,在其容器的右下角对齐一个 div
【发布时间】:2018-10-16 19:07:03
【问题描述】:

我需要在其红色容器“内容”的右下角显示黄色 div“图标”。

我的脚本有什么问题?

.root {
    display: inline-flex;
    background-color: red;
}

.content {
    display: flex;
    align-items: centerl;
    justify-content: centerl;
    height: 80px;
    width: 100%;
    background-color: red;
}

.icon {
    position: absolute;
    right: 0;
    bottom:0;
    background-color: yellow;
}
<div class="root">
    <div class="content">
        content
    </div>
    <div class="icon">
      icon
    </div>
</div>

【问题讨论】:

    标签: html css flexbox


    【解决方案1】:

    你可以使用 flex end 属性 align-self: flex-end; 来代替位置

    见下面的代码sn-p:

    .root {
      display: inline-flex;
      background-color: red;
    }
    
    .content {
      display: flex;
      align-items: center;
      justify-content: center;
      height: 80px;
      width: 100%;
      background-color: red;
    }
    
    .icon {
       align-self: flex-end;
       background-color: yellow;
    }
    <div class="root">
      <div class="content">
        content
      </div>
      <div class="icon">
        icon
      </div>
    </div>

    【讨论】:

    • align-items:center 定义了弹性项目在当前行沿横轴布局的默认行为。您可以将其视为横轴的 justify-content 版本,justify-content:center 定义项目沿线居中。
    【解决方案2】:

    .root {
      display: inline-flex;
      background-color: red;
      position: relative;
    }
    
    .content {
      display: flex;
      align-items: centerl;
      justify-content: centerl;
      height: 80px;
      width: 100%;
      background-color: red;
    }
    
    .icon {
      position: absolute;
      right: 0;
      bottom:0;
      background-color: yellow;
    }
    <div class="root">
      <div class="content">
        content
      </div>
      <div class="icon">
        icon
      </div>
    </div>

    添加 .root 元素

    position: relative;
    

    【讨论】:

    • 为什么需要亲戚?
    • @Radex 检查this SO answer 以获得更清晰的解释
    • @Radex 使绝对位置保持在该元素内而不会外出。
    【解决方案3】:

    在您呈现的 HTML 结构中,.icon 元素不在.container 元素内部。所以不能与之相关。如果你改变结构并给.container元素position: relative,它会起作用。

    .root {
      display: inline-flex;
      background-color: red;
    }
    
    .content {
      display: flex;
      align-items: centerl;
      justify-content: centerl;
      height: 80px;
      width: 100%;
      background-color: red;
      position: relative;
    }
    
    .icon {
      position: absolute;
      right: 0;
      bottom:0;
      background-color: yellow;
    }
    <div class="root">
      <div class="content">
        content
        <div class="icon">
          icon
        </div>
      </div>
    </div>

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2022-06-18
      • 2017-07-30
      • 2017-03-10
      • 2021-04-18
      • 1970-01-01
      • 2020-11-06
      • 1970-01-01
      • 2017-12-11
      相关资源
      最近更新 更多