Home > Back-end >  How do you vertically align text using line-height for a css grid row element created using grid-tem
How do you vertically align text using line-height for a css grid row element created using grid-tem

Time:10-31

Its important that I use grid-template-rows to define the height of the elements as I want the proportions to stay accurate dynamically. However I don't know how to get the line-height of a given row to center its text vertically. Im resorting to some hacky padding stuff that I dont like. Example code below

#wrapper {
  height: 100%;
}

#profile {
  height: 100%;
  border: 1px solid black;
  display: grid;
  grid-template-rows: 5fr 1fr 1fr 1fr 1fr 1fr;
}

#pfp {
  height: 85%;
  width: 85%;
  border: 1px solid black;
  margin: 1.5em auto 1.5em auto;
}

.info {
  border: 1px solid black;
  font-weight: bold;
  padding-left: 1em;
  line-height: 100%;
}
<section id="wrapper">
  <h3 id="heading">Heading</h3>
  <div id="profile">
    <div id="imageFrame">
      <div id="pfp"></div>
    </div>
    <div class="info" id="name">Name: </div>
    <div class="info" id="username">Username: </div>
    <div class="info" id="email">Email: </div>
    <div class="info" id="location">Location: </div>
    <div class="info" id="occupation">Occupation: </div>
  </div>
</section>
<iframe name="sif1" sandbox="allow-forms allow-modals allow-scripts" frameborder="0"></iframe>

Setting line-height by percentage does not work but as the height of the element is relative to the height of the browser window, I dont know how to get it to center the text of the .info elements

CodePudding user response:

just need to apply flexbox to the elements: .info { display: flex; }. Then you can center the text by using: .info { align-items: center; }

#profile {
  min-height: 80vh;
  border: 1px solid black;
  display: grid;
  grid-template-rows: 5fr 1fr 1fr 1fr 1fr 1fr;
}

#pfp {
  height: 60%;
  width: 85%;
  border: 1px solid black;
  margin: 1.5em auto 1.5em auto;
}

.info {
  border: 1px solid black;
  font-weight: bold;
  padding-left: 1em;
  line-height: 100%;
  display: flex;
  align-items: center;
}
<section id="wrapper">
  <h3 id="heading">Heading</h3>
  <div id="profile">
    <div id="imageFrame">
      <div id="pfp"></div>
    </div>
    <div class="info" id="name">Name: </div>
    <div class="info" id="username">Username: </div>
    <div class="info" id="email">Email: </div>
    <div class="info" id="location">Location: </div>
    <div class="info" id="occupation">Occupation: </div>
  </div>
</section>
<iframe name="sif2" sandbox="allow-forms allow-modals allow-scripts" frameborder="0"></iframe>

  • Related