【问题标题】:Align buttons to bottom-left corner using flex使用 flex 将按钮对齐到左下角
【发布时间】:2021-07-13 15:20:48
【问题描述】:

我需要在父 div 的左下角对齐一个 div,就像这个 Bootstrap docs flex 演示链接中的第二个示例一样:https://getbootstrap.com/docs/4.0/utilities/flex/#align-items

在我的例子中,唯一的区别是其中一个子项是图像。无论屏幕大小如何,都应该进行对齐。

在以下示例中,按钮容器 div 需要对齐 flex-container 的左下角。

编辑: 按钮容器应出现在图像本身上,而不是图像下方。

.flex-container{
  display: flex;
  align-items: flex-end !important;
  border: solid 1px red;
}

.button-container{
  border: solid 1px green;
}
<div class="flex-container">
    <img src="https://www.webkit.org/blog-files/acid3-100.png" />
    <div class="button-container">
        <button>Button 1</button>
        <button>Button 2</button>
    </div>
</div>

【问题讨论】:

    标签: html css


    【解决方案1】:

    您在代码中遗漏的是flex-direction。默认情况下它将是行,因此 div 并排出现。您需要将值指定为column

    .flex-container{
      display: flex;
      flex-direction: column;
      align-items: flex-start !important;
      border: solid 1px red;
      position: relative;
    }
    
    .button-container{
      border: solid 1px green;
      display: flex;
      position: absolute;
      left: 20px;
      top: 50px;
    }
    <div class="flex-container">
        <img src="https://www.webkit.org/blog-files/acid3-100.png" />
        <div class="button-container">
            <button>Button 1</button>
            <button>Button 2</button>
        </div>
    </div>

    编辑:制作按钮position: absolute。您可以使用 sn-p 中已经提到的 left/top 属性根据您的要求对齐它们。

    【讨论】:

    • 完美。你能也看看我的编辑吗?
    • 当然,您可以使用绝对位置使按钮位于图像上方,并根据需要使用左/右/上/下属性对齐它们。会在上面的sn-p中更新
    • 已更新我的答案@joym8。你能验证一下吗
    • 它正在创建并排的 div。
    • 你能验证我答案中的 sn-p 吗?
    【解决方案2】:

    如果您事先知道图片的尺寸,我建议您使用背景属性

    .flex-container{
      display: flex;
      align-items: flex-end !important;
      border: solid 1px red;
      background-image: url("https://www.webkit.org/blog-files/acid3-100.png");
      background-repeat: no-repeat;
      background-size: cover;
      width: 780px;
      height: 619px;
    }
    
    .button-container{
      border: solid 1px green;
    }
    <div class="flex-container">
        <div class="button-container">
            <button>Button 1</button>
            <button>Button 2</button>
        </div>
    </div>

    【讨论】:

    • 不幸的是,在我的情况下,设置背景会导致更多问题,因为图像是营销图像并且上面有文字。任何因缩小/扩大屏幕尺寸而造成的剪裁都是不可接受的。
    猜你喜欢
    • 2022-11-27
    • 1970-01-01
    • 2019-01-16
    • 1970-01-01
    • 2011-05-06
    • 2014-06-21
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多