AGamePlayer
AGamePlayer

Reputation: 7734

What's the easiest way to force n elements be showed in a row?

Here is a very detailed demo of what I want:

I want to keep the HTML as group1 and use pure CSS to make it like group2.

I hope:

  1. Only use CSS. The width of the button should be defined in the CSS;
  2. The parent div of those buttons are not in a fixed width.
  3. The 0 button should be in the middle (what I did is to put two buttons and hide them)
  4. The button should be aligned one to one with the same margin between them. And the margin should be a dynamic value since the parent div is flexible.

I tried a lot of ways but failed to reach the perfect result. Is there anyone can drop any tips? Thanks!

button{
width:27px;
height:27px;
margin:5px;
cursor:pointer;
}
.placeholder {opacity:0}
<div class="group1">
  <button>1</button>
  <button>2</button>
  <button>3</button>
  <button>4</button>
  <button>5</button>
  <button>6</button>
  <button>7</button>
  <button>8</button>
  <button>9</button>
  <button>0</button>
</div>

<hr>

<div class="group2">
  <button>1</button>
  <button>2</button>
  <button>3</button>
  <br>
  <button>4</button>
  <button>5</button>
  <button>6</button>
  <br>
  <button>7</button>
  <button>8</button>
  <button>9</button>
  <br>
  <button class="placeholder">0</button>
  <button>0</button>
  <button class="placeholder">0</button>
</div>

Upvotes: 2

Views: 305

Answers (2)

Temani Afif
Temani Afif

Reputation: 273561

The easiest way is CSS grid:

.group1 {
  display: inline-grid;
  grid-template-columns: repeat(3, 1fr); /*Or simply : 1fr 1fr 1fr*/
  grid-gap: 10px;
}

.group1 button:last-child {
  transform: translate(calc(100% + 10px));
}

button {
  width: 27px;
  height: 27px;
  cursor: pointer;
}
<div class="group1">
  <button>1</button>
  <button>2</button>
  <button>3</button>
  <button>4</button>
  <button>5</button>
  <button>6</button>
  <button>7</button>
  <button>8</button>
  <button>9</button>
  <button>0</button>
</div>

Upvotes: 3

Amr Noman
Amr Noman

Reputation: 2647

This should do it using flexbox, you can change the container's width and the items will adjust accordingly:

button{
  width: 27px;
  height:27px;
  cursor:pointer;
  margin-top: 5px;
  margin-bottom: 5px;
}

button:not(:nth-child(3n)) { 
  margin-right: calc((100% - 27px * 3) / 2);
}

button:last-child {
  margin-right: 0;
}
 
.group1 {
   display: flex;
   flex-wrap: wrap;
   justify-content: center; 
   width: 33%;
}
<div class="group1">
  <button>1</button>
  <button>2</button>
  <button>3</button>
  <button>4</button>
  <button>5</button>
  <button>6</button>
  <button>7</button>
  <button>8</button>
  <button>9</button>
  <button>0</button>
</div>

Upvotes: 1

Related Questions