Collin
Collin

Reputation: 1875

How can I make sibling elements take on the width of the largest sibling?

I have 2-3 li inside of a ul. The ul has a set width. The text in the li tags will vary but we want to maintain a minimum width of 100px for each of them. For li with more text we want to ensure that there is 15 pixels of padding on their left and right.

Ideally, all of the li would be identical in width i.e. they would all take on the width of the largest li. min-width:100px ensures that all of the li will be the same width when they are all below 100 pixels, but if one is above this width, the others must scale up to match.

Can I achieve this using only css/html? I believe I can solve this somewhat easily with javascript but I'd like to solve it without it.

jsfiddle: https://jsfiddle.net/a8ho4b04/3/

html:

<ul>
  <li class="li-1">--- --------</li>
  <li class="li-2">------- ------ ------</li>
  <li class="li-3">---</li>
</ul>

css:

ul {
  display: block;
  width: 450px;
}
li {
  display: inline-block;
  padding: 5px 15px;
  border-radius: 3px;
  box-sizing: border-box;
  border: 1px solid black;
  min-width: 100px;
  text-align: center;
}
.li-1 {
  background-color: green;
}
.li-2 {
  background-color: yellow;
}
.li-3 {
  background-color: cyan;
}

Upvotes: 2

Views: 726

Answers (2)

Paulie_D
Paulie_D

Reputation: 115044

Flexbox

ul {
  width: 450px;
  display: flex;
  list-style: none;
}
li {
  flex: 1;
  border-radius: 3px;
  padding: 5px 15px;
  box-sizing: border-box;
  border: 1px solid black;
  min-width: 100px;
  text-align: center;
}
.li-1 {
  background-color: green;
}
.li-2 {
  background-color: yellow;
}
.li-3 {
  background-color: cyan;
}
<ul>
  <li class="li-1">--- --------</li>
  <li class="li-2">------- ------ ------</li>
  <li class="li-3">---</li>
</ul>

CSS Tables

ul {
  width: 450px;
  display: table;
  table-layout: fixed;
  list-style-type: none;
}
li {
  display: table-cell;
  border-radius: 3px;
  padding: 5px 15px;
  box-sizing: border-box;
  border: 1px solid black;
  min-width: 100px;
  text-align: center;
}
.li-1 {
  background-color: green;
}
.li-2 {
  background-color: yellow;
}
.li-3 {
  background-color: cyan;
}
<ul>
  <li class="li-1">--- --------</li>
  <li class="li-2">------- ------ ------</li>
  <li class="li-3">---</li>
</ul>

Upvotes: 3

Craig Harley
Craig Harley

Reputation: 332

You can give them a fixed width (in pixels), or a minimum width (which can be relative).

Upvotes: -1

Related Questions