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

How to align element to right side of div box?

如何将元素对齐到 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;
}

我需要 tree 放在 foo 的右上角。

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

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>

Flex 示例

#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>

给#tree float:right。

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

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

一种方法是使用 position: relative / absolute 组合:

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

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

有可能 position:absolute

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

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

像这样更新您的 css。 #tree div 永远在 #foo

的右上角

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

    #tree {
        width: 100px;
        height: 30px;
        background: #000000;
        position: absolute;
        top: 0;
        right: 0;
    }