Search code examples
htmlcsscss-grid

CSS grid item always on a single line


I'm trying to create a simple layout: there are some labels that have to be placed on different lines because there isn't enough space for all. I use Grid to do this.

My code works but I prefer that each label should be on a single line.

Now:

enter image description here

The label a very very very very long label should be on a single line not on two.

The code:

.container {
  background-color: tomato;
  width: 100%;
  color: black;
  display: grid;
  grid-template-columns: repeat(5, auto);
  grid-gap: 5px 5px;
}

.child {
  border: 1px solid black;
}
<div class="container">
  <div class="child">apple</div>
  <div class="child">social</div>
  <div class="child">cat</div>
  <div class="child">computer</div>
  <div class="child">table</div>
  <div class="child">photograph</div>
  <div class="child">future of the world</div>
  <div class="child">something</div>
  <div class="child">yellow</div>
  <div class="child">romance</div>
  <div class="child">dictionary</div>
  <div class="child">a very very very very long label</div>
</div>

How can I have to change my code?


In this codepen I use the code posted by @Saksham and I change only text-align from center to left.

Changing windows size I get this:

enter image description here

But I want this:

enter image description here

As you can see, there is less free space around dictionary and a very very very very long label labels


Solution

  • I would rather advice you to switch to flexbox. Your tiles are unnecessarily taking up space if a vertically placed tile has more text.

    .container {
      background-color: #aaa;
      width:400px;
      display:flex;
      flex-wrap: wrap;
    }
    .container:after {
      flex: auto;
      content:'';
      flex-grow: 100;
    }
    
    .child {
      margin: 2px 1px;
      padding: 10px;
      background-color: #888;
      white-space: nowrap;
      flex:1;
      text-align: center;
    }
    <div class="container">
      <div class="child">apple</div>
      <div class="child">social</div>
      <div class="child">cat</div>
      <div class="child">computer</div>
      <div class="child">table</div>
      <div class="child">photograph</div>
      <div class="child">future of the world</div>
      <div class="child">something</div>
      <div class="child">yellow</div>
      <div class="child">romance</div>
      <div class="child">dictionary</div>
      <div class="child">a very very very very long label</div>
    </div>