水平排列元素的底部对齐

最终运行结果
运行结果
HTML结构

<div class="parent">
    <div class="child" style="height: 200px; width:50px; background-color: red;">red</div>
    <div class="child" style="height: 140px; width:50px; background-color: blue;">blue</div>
    <div class="child" style="height: 100px; width:50px; background-color: yellow;">yellow</div>
    <div class="child" style="height: 180px; width:50px; background-color: green;">green</div>
</div>

这里的parent和child高度未知

1. absolute + bottom

首先想到的是用absolute定位来做,但这不是一个好方法原因基于两点:
- 绝对定位之后子元素脱离文档流会相互覆盖,需要对每个子元素指定不同的left或者margin
- 由于子元素脱离文档流,父元素高度会收缩,导致看不到完整的子元素。解决方法是给父元素指定宽度或者对子元素指定一个负的bottom,而且这个高度或者bottom要至少等于最高子元素。但是子元素高度并不知道,所以这不是个好方法。

    .parent {
        position: relative;
        /*height: 200px;*/
    }
    .child {
        position: absolute;
        bottom: -200px;  // 不指定此属性会导致子元素只有底部部分可见
        width: 50px;
    }

2. vertical-align + inline-block

指定子元素为内联块元素,然后指定他们的垂直对齐方式

.child {
    display: inline-block;
    vertical-align: bottom;
}

vertical-align不同于text-align,是指定自身相对于父元素的垂直对齐方式
这种方式简单而且只在子元素上设置样式即可,兼容性也非常好

3. flex + align-items

在父元素上设置

.parent {
    display: flex;
    align-items: flex-end;
}

这种方式也非常简单,只需在父元素上设置样式,但是兼容性不好

完整代码示例

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Document</title>
    <style>
        /*第二种*/
        .child {
            display: inline-block;
            vertical-align: bottom;
        }

        /*第三种*/
        /*.parent {
            display: flex;
            align-items: flex-end;
        }*/
    </style>
</head>
<body>
    <div class="parent">
        <div class="child" style="height: 200px; width:50px; background-color: red;">red</div>
        <div class="child" style="height: 140px; width:50px; background-color: blue;">blue</div>
        <div class="child" style="height: 100px; width:50px; background-color: yellow;">yellow</div>
        <div class="child" style="height: 180px; width:50px; background-color: green;">green</div>
    </div>
</body>
</html>
  • 3
    点赞
  • 8
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值