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

Let*_*e ヅ 0 html css css-position

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

我的 div

<div id="foo">
    <div id="tree">Some Text here</div>
</div>
Run Code Online (Sandbox Code Playgroud)

我的CSS

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

#tree {
    width: 100px;
    height: 30px;
    background: #000000;
}
Run Code Online (Sandbox Code Playgroud)

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

Jer*_*ris 8

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

margin-left: auto;
Run Code Online (Sandbox Code Playgroud)

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

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

保证金示例

margin-left: auto;
Run Code Online (Sandbox Code Playgroud)
#foo {
    display: block;
    width: 500px;
    height: 500px;
    background: #5e5e5e;
}

#tree {
    width: 100px;
    height: 30px;
    background: #000000;
    margin-left: auto;
}
Run Code Online (Sandbox Code Playgroud)

浮动示例

<div id="foo">
    <div id="tree">Some Text here</div>
</div>
Run Code Online (Sandbox Code Playgroud)
#foo {
    display: block;
    width: 500px;
    height: 500px;
    background: #5e5e5e;
}

#tree {
    width: 100px;
    height: 30px;
    background: #000000;
    float: right;
}
Run Code Online (Sandbox Code Playgroud)

弹性示例

<div id="foo">
    <div id="tree">Some Text here</div>
</div>
Run Code Online (Sandbox Code Playgroud)
#foo {
    display: flex;
    justify-content: flex-end;
    width: 500px;
    height: 500px;
    background: #5e5e5e;
}

#tree {
    display: flex;
    width: 100px;
    height: 30px;
    background: #000000;
}
Run Code Online (Sandbox Code Playgroud)


Pus*_*ama 5

将 float:right 赋予#tree。

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

#tree {
	float: right;
    width: 100px;
    height: 30px;
    background: #000000;
}
Run Code Online (Sandbox Code Playgroud)
  <div id="foo">
		<div id="tree">Some Text here</div>
	</div>
Run Code Online (Sandbox Code Playgroud)