将按钮固定在div右侧

54

http://jsfiddle.net/kn5sH/

我需要添加什么才能使按钮粘在div的右侧,与标题在同一行上?

HTML:

<div>
    <h1> Ok </h1>
    <button type='button'>Button</button>
</div>

CSS:

div {
    background: purple;
}

div h1 {
    text-align: center;
}

div button {
}
更具体地说:
  1. 按钮的右边应该与div的右边缘相隔x像素。
  2. 它应该与页眉在同一行上。
  3. 应该包含在div中(类似浮动或相对定位的内容会使其在视觉上从div中弹出)

有哪些CSS技术可以实现这一点?谢谢。

8个回答

73

通常我会建议使用浮动,但考虑到你的三个要求,我建议使用以下方法:

position: absolute;
right: 10px;
top: 5px;

别忘了在父级div上加上position: relative;

演示


谢谢,这个很好用。我尝试了一下但是忘记加上“top”属性,结果它被推到了div下面。 - Andrew

39

另一个解决方案:改变页面边距。根据按钮的兄弟元素,需要修改display属性。

button {
  display: block;
  margin-left: auto;
  margin-right: 0;
}

25

这取决于您想要实现什么。

如果您只是想将其置于右侧,则不建议使用绝对定位,因为它会在后面引起很多问题。

HTML 也可以保持不变:

HTML

<div>
    <h1> Ok </h1>
    <button type='button'>Button</button>
</div>

那么CSS应该是这样的:

CSS

div {
    background: purple;
    overflow: hidden;
}

div h1 {
    text-align: center;
    display: inline-block;
    width: 100%;
    margin-right: -50%;
}

div button {
    float: right;
}

你可以在这里看到它的实际应用:http://jsfiddle.net/azhH5/

如果您可以更改HTML,则会变得更简单:

HTML

<div>
    <button type='button'>Button</button>
    <h1> Ok </h1>
</div>

CSS

div {
    background: purple;
    overflow: hidden;
}

div h1 {
    text-align: center;
}

div button {
    float: right;
    margin-left: -50%;
}

您可以在以下链接中查看其实际效果:http://jsfiddle.net/8WA3k/1/

如果您想要将按钮与文本放在同一行,可以通过以下方法实现:

HTML

<div>
    <button type='button'>Button</button>
    <h1> Ok </h1>
</div>

CSS

div {
    background: purple;
    overflow: hidden;
}

div h1 {
    text-align: center;
}

div button {
    float: right;
    margin-left: -50%;
    margin-top: 2em;
}

你可以在这里看到它的实际效果:http://jsfiddle.net/EtqVh/1/

显然,在最后一个示例中,您需要调整<h1>指定字体大小的上边距。

编辑:

正如您所看到的,它没有从<div>弹出来,而是仍然在内部。这通过两个方法实现:在<button>上使用负边距以及在<div> 上使用 overflow: hidden;

第二次编辑:

我刚看到您还希望它离右侧边缘有一点距离。这个方法很容易实现。只需在<button>上添加margin-right: 1em;,就像这样:

div {
    background: purple;
    overflow: hidden;
}

div h1 {
    text-align: center;
}

div button {
    float: right;
    margin-left: -50%;
    margin-top: 2em;
    margin-right: 1em;
}
你可以在这里看到它的效果:http://jsfiddle.net/QkvGb/

你能进一步阐述一下 overflow: hidden 在这种情况下如何帮助解决问题吗?还有那个负边距。 - JohnnyQ

6
div {
 display: flex;
 flex-direction: row-reverse;
}

1
虽然这段代码可能回答了问题,但添加代码解释会对未来的读者有所帮助。 - Boken

5
<div>
    <h1> Ok </h1>
    <button type='button'>Button</button>
    <div style="clear:both;"></div>
</div>

css

div {
    background: purple;
}

div h1 {
    text-align: center;
}

div button {
    float: right;
    margin-right:10px;

}

谢谢。这与上面的代码一样有效,我也尝试过这种方法,但在按钮元素下没有应用“clear:both”。我接近了! - Andrew

2
使用position属性
style="position: absolute;right:0;top:0"

1
margin-left:  auto;

对我来说已经足够了。


0

将CSS更改为以下内容:

div button {
position:absolute;
    right:10px;
    top:25px;
}

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