48

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 技术来做到这一点?谢谢。

4

8 回答 8

65

通常我会建议浮动,但根据您的 3 个要求,我建议这样做:

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

不要忘记position: relative;父 div

演示

于 2013-05-30T09:24:59.983 回答
25

另一种解决方案:更改边距。根据按钮的兄弟姐妹,display应该进行修改。

button {
  display: block;
  margin-left: auto;
  margin-right: 0;
}
于 2016-05-25T09:42:30.650 回答
22

这取决于您想要实现的目标。

如果你只是想把它放在右边,那么我建议不要使用绝对位置,因为它会打开一整罐蠕虫。

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>overflow: hidden;<div>

编辑2:

我刚刚看到你也希望它离右边的边距有点远。使用这种方法很容易实现。只需添加margin-right: 1em;<button>,如下所示:

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/

于 2013-05-30T10:16:33.890 回答
6
<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;

}
于 2013-05-30T09:26:31.143 回答
5
div {
 display: flex;
 flex-direction: row-reverse;
}
于 2019-03-28T10:41:10.543 回答
2

使用位置属性

style="position: absolute;right:0;top:0"
于 2015-03-12T13:50:36.387 回答
0

更改CSS如下:

div button {
position:absolute;
    right:10px;
    top:25px;
}
于 2013-05-30T09:58:16.763 回答
0
margin-left:  auto;

对我来说足够了

于 2022-02-08T18:28:10.863 回答