跳到主要内容

最高子元素

提示

问题: 父元素内多个子元素,子元素根据内容确定高度,把所有子元素的高度变为最高子元素的高度

一、Flex 布局


解决方案: 直接在 flex 容器上,将 align-items 设为 stretch 即可

实时编辑器
function Test(props) {
    const containerStyle = {
        width: '200px',
        height: '600px',
        display: 'flex',
        alignItems: "stretch",
        justifyContent: "space-between",
        flexWrap: "wrap",
        backgroundColor: "blue"
    }
    const itemSpanStyle = {
        width: "100px",
        backgroundColor: "red"
    }
    return (
        <div style={ containerStyle }>
            <div style={ itemSpanStyle }>哒哒哒哒哒</div>
            <div style={ itemSpanStyle }>嘻嘻</div>
            <div style={ itemSpanStyle }>红红火火恍恍惚惚哈哈哈哈哈哈哈你哈哈哈哈</div>
        </div>
    );
}
结果
Loading...

二、Table 布局


解决方案: 设置父元素为display: table,子元素为height: 100%; display: table-cell;

实时编辑器
function Test(props) {
    const containerStyle = {
        width: '400px',
        height: '600px',
        display: 'table',
        alignItems: "stretch",
        justifyContent: "space-between",
        flexWrap: "wrap",
        backgroundColor: "blue"
    }
    const itemSpanStyle1 = {
        width: "30%",
        height: "100%",
        display: "table-cell",
        backgroundColor: "red"
    }
    const itemSpanStyle2 = {
        width: "20%",
        height: "100%",
        display: "table-cell",
        backgroundColor: "red"
    }
    const itemSpanStyle3 = {
        width: "50%",
        height: "100%",
        display: "table-cell",
        backgroundColor: "red"
    }
    return (
        <div style={ containerStyle }>
            <div style={ itemSpanStyle1 }>哒哒哒哒哒</div>
            <div style={ itemSpanStyle2 }>嘻嘻</div>
            <div style={ itemSpanStyle3 }>红红火火恍恍惚惚哈哈哈哈哈哈哈你哈哈哈哈</div>
        </div>
    );
}
结果
Loading...