如何将元素对齐到 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 的右上角。

原文由 LetGame ヅ 发布,翻译遵循 CC BY-SA 4.0 许可协议

阅读 410
2 个回答

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

 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>

原文由 Jeremy Harris 发布,翻译遵循 CC BY-SA 4.0 许可协议

将 float:right 赋予#tree。

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

原文由 Pushprajsinh Chudasama 发布,翻译遵循 CC BY-SA 4.0 许可协议

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题