html - 动态元素并排

标签 html css

我想并排放置两个元素,但按钮元素应占用尽可能多的空间,以便将所有文本保持在一行中。 h1 元素应根据按钮元素占用的空间大小在必要时换行到第二行。

基本上,我想支持动态更改文本长度,而不需要为 h1 或按钮元素定义静态宽度。这有可能实现吗?

链接到我的 Fiddle .

section {
  width: 600px;
}

h1 {
  float: left;
  /* Width can't be used here, cos the texts are different length at different times */
  width: 400px;
}

button {
  float: right;
  margin-top: 20px;
}
<section>
  <!-- Header should wrap to second if needed, based on how much button element uses space -->
  <h1>Dynamic text that should wrap to second line if needed, because the text is sometimes pretty long</h1>
  <!-- Button should use as much space as possible to fit the text on one line-->
  <button>Dynamic button text</button>
</section>

最佳答案

这是 flexbox 解决方案。添加display: flex;到容器元素(在本例中为 <section> )和 flex-grow: 1到标题 - 这会使标题扩展以填充可用空间。

一个副作用是默认情况下按钮将垂直拉伸(stretch)(以匹配标题的高度)。您可以通过显式设置按钮的 height 来说明这一点。 ,或者将按钮包装在 <div> 中.如果你这样做,新的 <div>将垂直拉伸(stretch),但按钮将保持其正常大小。

section {
  width: 600px;
  display: flex;
}

h1 {
  flex-grow:1;
  width: 400px;
}

button {
  margin-top: 20px;
}

这是在 fork of your fiddle 中运行的(我在按钮周围添加了额外的 <div>)。

关于html - 动态元素并排,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49984630/

相关文章:

css - 使用 Bootbusiness 主题在 Twitter Bootstrap 中设置堆叠选项卡导航的样式

jquery - 需要在每次鼠标移动时更改背景位置

javascript - 如何使用 Javascript 创建 &lt;style&gt; 标签?

JavaScript 定时器事件

javascript - Sublime Text 2 自动建议自动完成的文件

javascript - div内容互相覆盖

html -::-ms-clear 伪元素的 CSS 规则未出现在 IE11 开发工具中,规则并不总是有效?

javascript - &lt;!DOCUMENT html> 在JS脚本中是否触发 "use strict"?

javascript - ExtJS - 如何自定义按钮?

javascript - Electron : How to print only a part of html (div) in electron silently?