使用 Flexbox 将元素对齐到角落

15
我试图使用 Flexbox 将四个元素放在一个 flex 容器的四个角上,但是遇到了困难。我无法弄清如何对单个 flex 项进行内容对齐。每次尝试时,它都会将 flex 容器的所有内容全部靠左或靠右(或者根据主轴靠上或靠下)。
HTML:
<div class="container">
    <div class="top-left">
         TL
    </div>
    <div class="top-right">
        TR
    </div>
    <div class="bottom-left">
        BL
    </div>
    <div class="bottom-right">
       BR
    </div>
</div>

这是我的 CSS:

.container {
    display: -webkit-flex;
    background-color:#ccc;
}

.top-left {
 /* ? */
}

.top-right {

}

.bottom-left {

}

.bottom-right {

}

这里有一个示例演示了我想要做的事情:

http://jsfiddle.net/JWNmZ/8/


3
请在您的问题中包含代码。始终如此。 - j08691
1
抱歉。感谢您的编辑。我想我那样做是因为我没有任何可以添加的代码,我只是可悲地卡住了。 - sma
2个回答

12

这里是一个方法(为了清晰起见省略前缀):http://jsfiddle.net/JWNmZ/10/

.container {
    display: flex;
    flex-wrap: wrap;
    background-color:#ccc;
}

.top-left {
    flex: 50%; 
}

.top-right {
    flex: 50%;
    text-align: right;
}

.bottom-left {
    flex: 50%;
}

.bottom-right {
    flex: 50%;
    text-align: right;
}

每个弹性项占据主轴的50%,我使用了flex-wrap.bottom-*类推到下一行。这很简单,关键真的是使用flex-wrap - Jason
啊,太完美了。谢谢你。 - sma
3
我发现当使用任意高度时,这个方法不能将底部项目与角落对齐。这里是一个稍微修改后的方法,可以达到这一效果:http://jsfiddle.net/JWNmZ/25/ - Dominic K
你只需要: justify-content: space-between; align-content: space-between; - jake
在阿拉伯字母从右到左(rtl)的情况下,Flexbox中使用startend代替rightleft,这是主要的注意点(答案可能会有所改进)。因为没有了从左到右的方向,只有起始->结束:https://developer.mozilla.org/en-US/docs/Web/CSS/CSS_Flexible_Box_Layout/Basic_Concepts_of_Flexbox#Start_and_end_lines - David
1
这个方法比“position:absolute”的方法好吗? - Jack

-1

        #wrapper {
            width: 500px;
            height: 500px;
            background-color: red;
            display: flex;
            flex-flow: wrap row;
            justify-content: space-between;
        }
#wrapper>div{
display:flex;
flex-flow:wrap column;
justify-content:space-between;
}
        .child {
            width: 50px;
            height: 50px;
            background: yellow;
        }
<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
</head>

<body>
    <div id="wrapper">
        <div>
            <div class='child'></div>
            <div class='child'></div>
        </div>
        <div>
            <div class='child'></div>
            <div class='child'></div>
        </div>
    </div>
</body>

</html>


你的回答可以通过提供更多支持信息来改进。请编辑以添加进一步的细节,例如引用或文档,以便他人可以确认你的答案是正确的。您可以在帮助中心中找到有关如何编写良好答案的更多信息。 - Community

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接