首页 > 解决方案 > 如何将元素对齐到 div 框的右侧?

问题描述

如何将元素对齐到 div 框的右侧?

我的 div

<div id="foo">
    <div id="tree">Some Text here</div>
</div>

我的 CSS

#foo {
    display: block;
    width: 500px;
    height: 500px;
    background: #5e5e5e;
}

#tree {
    width: 100px;
    height: 30px;
    background: #000000;
}

我需要将树放在foo的右上角。

标签: htmlcsscss-position

解决方案


有几种方法可以做到这一点。一种方法是向树添加自动左边距:

margin-left: auto;

另一种选择是应用于float: right;树,这可能会或可能不会导致您需要的内容流。

最后,老实说,我的建议是只使用 flexbox。

保证金示例

#foo {
    display: block;
    width: 500px;
    height: 500px;
    background: #5e5e5e;
}

#tree {
    width: 100px;
    height: 30px;
    background: #000000;
    margin-left: auto;
}
<div id="foo">
    <div id="tree">Some Text here</div>
</div>

浮动示例

#foo {
    display: block;
    width: 500px;
    height: 500px;
    background: #5e5e5e;
}

#tree {
    width: 100px;
    height: 30px;
    background: #000000;
    float: right;
}
<div id="foo">
    <div id="tree">Some Text here</div>
</div>

弹性示例

#foo {
    display: flex;
    justify-content: flex-end;
    width: 500px;
    height: 500px;
    background: #5e5e5e;
}

#tree {
    display: flex;
    width: 100px;
    height: 30px;
    background: #000000;
}
<div id="foo">
    <div id="tree">Some Text here</div>
</div>


推荐阅读