我想并排放置两个元素,但按钮元素应占用尽可能多的空间,以便将所有文本保持在一行中。 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/