【问题标题】:self adjusting layout using flex使用 flex 自动调整布局
【发布时间】:2017-08-15 16:08:22
【问题描述】:

* {
	border: none;
	font-family: monospace;
}
html, body {height: 100%;}
body {
	display: flex;
	align-items: center;
	padding: 10px;
}
.container {
	background: #eee;
	box-shadow: 0 10px 30px -10px rgba(0,0,0,.45);
	margin: auto;
	width: 500px;	
	padding: 30px 20px 20px;
}

/* main css starts here */

.row {
	display: flex;
	margin-bottom: 10px
}

input {
	flex: 1;
	padding: 2px 10px;
	margin-left: 10px;
	border: dotted 1px #bbb;
	border-radius: 20px;
	background: #fefefe
}
<div class="container">
  <div class="row">
    <label>hey ya!</label>
    <input/>
  </div>
  <div class="row">
    <label>how are you?</label>
    <input/>
  </div>
  <div class="row">
    <label>i am fine</label>
    <input/>
  </div>
</div>

我希望所有标签都具有相同的宽度,其中宽度恰好等于最宽标签的内容宽度。我希望布局自动调整所有标签宽度。

现在,您可以看到标签的宽度不同。如果我想要相同宽度的标签,那么我必须添加一个 flex-basis 属性来标记项目或给它们一个 min-width 值。我不想做它们中的任何一个,因为我必须首先手动检查最宽标签元素的宽度,如果我更改字母间距或选择一些宽字体,布局将会中断。

在 XUL 中有一个 vbox 元素有助于进行这种布局,在 html 中我猜 table 可以用来这样做,但我正在寻找一个 flexbox 解决方案。

【问题讨论】:

  • 不能用 flexbox 完成 - flex 项目只能与与它们在同一行的项目相关,而不是与在其他行的项目相关。如果希望所有标签的宽度相同,则需要手动设置。
  • 您正在寻找display: table
  • @NiettheDarkAbsol 你能发个例子吗?
  • @adam 实际上我必须使用的字体是默认的操作系统字体。在默认字体更改的不同操作系统上。在 Ubuntu 上,默认字体是 Ubuntu,与 Roboto(我的 linux 发行版默认字体)相比要宽得多。如果我必须手动设置它,我无法定位所有操作系统。布局会在某些操作系统上中断。
  • @ArshadKhan - 然后正如 Niet 所说,使用 display: table - 它正是你想要的。

标签: html css flexbox


【解决方案1】:

正如 Niet 指出的,使用display: table

* {
	border: none;
	font-family: monospace;
}
html, body {height: 100%;}
body {
	display: flex;
	align-items: center;
	padding: 10px;
}
.container {
  display: table;
	background: #eee;
	box-shadow: 0 10px 30px -10px rgba(0,0,0,.45);
	margin: auto;
	padding: 30px 20px 20px;
}

/* main css starts here */

.row {
  display: table-row;
	margin-bottom: 10px
}

label {
  display: table-cell;
  padding: 5px;
}

input {
	padding: 2px 10px;
	margin-left: 10px;
	border: dotted 1px #bbb;
	border-radius: 20px;
	background: #fefefe
}
<div class="container">
  <div class="row">
    <label>hey ya!</label>
    <input/>
  </div>
  <div class="row">
    <label>how are you?</label>
    <input/>
  </div>
  <div class="row">
    <label>i am fine</label>
    <input/>
  </div>
</div>

【讨论】:

  • 为什么标签比contentWidth of howareyou? label + 10px(padding) 更宽?我希望它们完全等于 contentWidth + padding/margin。
  • @ArshadKhan - 10px 的输入有左边距(来自您的代码)
  • 不。我不认为那是因为左边距。 imagebin.ca/v/3WzAVOUdqD9M
  • @ArshadKhan margin 不适用于表格单元格。您必须包装标签和输入才能使用它。
  • @LGSon 好的,但我想知道为什么标签元素会占用额外的空格。它不完全等于第二个标签(最宽)元素的宽度。保证金现在不是问题。