Home > Mobile >  Reduce space between elements in a css grid layout
Reduce space between elements in a css grid layout

Time:08-17

I have a grid layout that looks like this:

enter image description here

I would like to reduce the whitespace between 'Job Role' and 'Company Name' & I cannot work out how to do this.

The container css looks like this:

.experience-child {
    display: grid;
    grid-template-columns: 2fr 6fr;
    grid-template-rows: repeat(5, 1fr);
    margin-bottom: 6em;
    font-family: 'Alumni Sans', sans-serif;
}

I have tried:

  • Adjusting row-gap with row-gap 0;
  • Adjusting margin-bottom and padding-bottom of the individual elements with negative values.
  • Adding grid-auto-rows: min-content; to the above container

Thank you very much.

HTML & CSS to replicate:

<div >
    <p >2001-2001</p>
    <p >Job Role</p>
    <p >Company Name</p>
    <ul >
        <li>this</li>
        <li>that</li>
        <li>other</li>
    </ul>
</div>
.experience-child {
    display: grid;
    grid-template-columns: 2fr 6fr;
    grid-template-rows: repeat(5, 1fr);
    margin-bottom: 6em;
    font-family: 'Alumni Sans', sans-serif;
}

.last {
    margin-bottom: 0;
}

.jobrole {
    font-weight: bold;
}

.company {
    grid-area: 2 / 2 / 3 / 3;
    font-weight: bold;
}

.job-blurb {
    grid-area: 3 / 2 / 5 / 3;
}

CodePudding user response:

grid-template-rows: repeat(5, 1fr); indicates that your grid has 5 rows of equal height. That's the height of the .experience-child container divided by 5.

There are many ways to reduce the whitespace between Job Role and Company Name:

  • You could reduce the height of the first row, by replacing it with e.g. grid-template-rows: 1em repeat(4, 1fr);

  • You could keep equal row height and move Job Role within its container with e.g. position: absolute; bottom: 0;, or padding-top: 1em;

  • You could place Company Name in the same container as Job Role by wrapping <p >Job Role</p><p >Company Name</p> in a new div

CodePudding user response:

Change grid-template-rows: repeat(5, 1fr); to grid-template-rows: repeat(1, 1fr);.

See the snippet below.

.experience-child {
  display: grid;
  grid-template-columns: 2fr 6fr;
  grid-template-rows: repeat(1, 1fr);
  margin-bottom: 6em;
  font-family: 'Alumni Sans', sans-serif;
  background-color: gold;
}

.last {
  margin-bottom: 0;
}

.jobrole {
  font-weight: bold;
}

.company {
  grid-area: 2 / 2 / 3 / 3;
  font-weight: bold;
}

.job-blurb {
  grid-area: 3 / 2 / 5 / 3;
}

p {
  margin: 0;
}
<div >
  <p >2001-2001</p>
  <p >Job Role</p>
  <p >Company Name</p>
  <ul >
    <li>this</li>
    <li>that</li>
    <li>other</li>
  </ul>
</div>

  • Related