如何在标题旁边放置一个按钮?

新手上路,请多包涵

我认为使用 float: right; 可以解决这个问题,但它会使按钮出现在 div 之外。我该如何解决这个问题?

HTML

 <div id="main">
  <h1>Title</h1> <button>Button</button>
</div>

CSS

 #main {
  width: 200px;
  border: 1px dotted black;
}
h1 {
  margin: 0;
}
button {
  float: right;
}

JSFiddle

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

阅读 709
2 个回答

最初的答案建议使用 inline-blockfloat 来定位元素,但从那以后事情就发生了变化。今天更灵活的解决方案是使用 flex

 #main {
  border: 1px dotted black;
  display: flex;
  align-items: center; /* Vertical align the elements to the center */
}

h1 {
  margin: 0;
}

button {
  margin-left: auto; /* Push this element to the right */
}
 <div id="main">
  <h1>Title</h1> <button>Button</button>
</div>

旧答案

给你的 h1 display: inline-block 让你的元素占据同一行……

 #main {
  width: 200px;
  border: 1px dotted black;
}
h1 {
  margin: 0;
    display: inline-block;
}
button {
  float: right;
}
 <div id="main">
  <h1>Title</h1> <button>Button</button>
</div>

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

试试这样:

 #main {
  width: 200px;
  border: 1px dotted black;
}
h1 {
  margin: 0;
}
button {
  float: right;
}
 <div id="main">
  <h1> Title <button>Button</button></h1>
</div>

JSFIDDLE 演示

或者您可以使用 display:inline 让它们并排出现。

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

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