Arshad Khan Arshad Khan -3 years ago 97
HTML Question

self adjusting layout using flex



* {
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>





I want all labels to have same width, where width is exactly equal to the content width of widest label. I want layout to automatically adjust all label width.

Right now, you can see the width of labels is different. If I want same width label then I have to either add a
flex-basis
property to label items or give them a
min-width
value. I dont want to do either of them as then I have to manually first check the width of widest label element and layout will break if I change letter spacing or choose some wide font.

In XUL there is a
vbox
element which helps to make such kind of layout and in html I guess table can be used to do so but I am looking for a flexbox solution.

Answer Source

Just as Niet pointed out, use 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>

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download