Home > Software engineering >  How can I allow multiple buttons to take up all the space within a div while having different text?
How can I allow multiple buttons to take up all the space within a div while having different text?

Time:10-09

I have 9 buttons that have text, within a div. They all have css that makes it so that they all take up 1/9 of the space.

div {
  border: 1px solid black;
  height:200px;
  width:200px;
  padding:0px;
}
button {
  width:calc(100% / 3);
  height:calc(100% / 3);
  border-radius:0px;
}
<div>
<button>Hello world!</button><button>Hello world!</button><button>Hello world!</button><br><button>Hello world!</button><button>Hello world!</button><button>Hello world!</button><br><button>Hello world!</button><button>Hello world!</button><button>Hello world!</button>
</div>

When they have the same text, they work perfectly fine and give me the desired result as you see above.

div {
  border: 1px solid black;
  height:200px;
  width:200px;
  padding:0px;
}
button {
  width:calc(100% / 3);
  height:calc(100% / 3);
  border-radius:0px;
}
<div>
<button>I am a different button!</button><button>Hello world!</button><button>Hello world!</button><br><button>I'm different too!</button><button>Hello world!</button><button>foo bar foo bar</button><br><button>Hello world!</button><button>Hello world!</button><button>So am I!</button>
</div>

When they have different text it gets all messed up. I also tried using flexbox, but it just made the buttons fill the height but wrap incorrectly.

What I want is a way to have 9 buttons in a rectangular div that are always 1/9 of the div's size, no matter what their text is. Another thing I need is that the buttons can scale to the div, in case someone resizes their screen or I need the div to be differently sized. If your solution uses JS/Jquery, that's okay.

I'm not an expert at css. How can I fix this? Is there a better way of doing this? Thank you.

CodePudding user response:

This works using display: flex and flex-wrap: wrap:

div {
  border: 1px solid black;
  height:200px;
  width:200px;
  padding:0px;
  display: flex;
  flex-wrap: wrap;
}
button {
  width: 33.333%;
  height: 33.333%;
  border-radius:0px;
}
<div>
<button>I am a different button!</button><button>Hello world!</button><button>Hello world!</button><br><button>I'm different too!</button><button>Hello world!</button><button>foo bar foo bar</button><br><button>Hello world!</button><button>Hello world!</button><button>So am I!</button>
</div>

  • Related