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

7

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

这些都对你没用吗?这个经常被问到的问题在SO和互联网上得到了广泛回答。 - Rob
你可以使用CSS的Float属性,例如“float: right;”。请查看以下链接:https://stackoverflow.com/questions/27600267/put-element-to-the-right-side-of-a-div - Karan Raiyani
5个回答

14

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

margin-left: auto;

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

最后,我的真诚建议就是使用flexbox。

Margin示例

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


我添加了另外几个选项,以防内容流不符合您的要求。 - Jeremy Harris

5

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


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


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>


如果我设置position:absolute,它会定位到页面而不是#foo。 - LetGame ヅ
定位的基本规则:absolute 只能在父元素相对定位的情况下使用。请查看 #foo 的 CSS。 - Manohar

0

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


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接