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

时间:2019-12-27 13:13:13

标签: html css css-position

如何将元素与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 的右上方放置

5 个答案:

答案 0 :(得分:5)

有几种方法可以完成此操作。一种方法是在树上添加自动左边距:

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>

答案 1 :(得分:3)

让float:转到#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>

答案 2 :(得分:1)

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>

答案 3 :(得分:1)

像这样更新您的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;
    }

答案 4 :(得分:0)

一种方法是使用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>

相关问题