CupOfGreenTea
CupOfGreenTea

Reputation: 419

How to place text at the bottom of a div inside a grid?

I am trying to place the text at the bottom of the div but even when I set it to position: relative; bottom: 0 it doesn't work. I also tried vertical alignment but it doesn't work:

* {
  box-sizing: border-box;
}

body {
  padding: 0;
  margin: 0;
}

.mainContainer {
  display: grid;
  width: 100vw;
  height: 100vh;
  place-items: center;
}

.subContainer {
  display: grid;
  grid-template-columns: 20% 80%;
  width: 60%;
}

.anotherDiv {
  background-color: rgb(195, 171, 171);
}

img {
  width: 100%;
  height: auto;
}

.textForBottom {
  position: relative;
  bottom: 0;
}
<div class="mainContainer">
  <div class="subContainer">
    <img src="https://static01.nyt.com/images/2021/09/14/science/07CAT-STRIPES/07CAT-STRIPES-mediumSquareAt3X-v2.jpg" alt="cat" />
    <div class="anotherDiv">
      <span class="textForBottom">
         This text should be at the bottom in the div that contains it
      </span>
    </div>
  </div>
</div>

CodePen

Upvotes: 1

Views: 123

Answers (2)

iorgu
iorgu

Reputation: 3053

By making the child absolute and its parent relative.

* {
  box-sizing: border-box;
}

body {
  padding: 0;
  margin: 0;
}

.mainContainer {
  display: grid;
  width: 100vw;
  height: 100vh;
  place-items: center;
}

.subContainer {
  display: grid;
  grid-template-columns: 20% 80%;
  width: 60%;
}

.anotherDiv {
  background-color: rgb(195, 171, 171);
  position: relative;
  /*new code*/
}

img {
  width: 100%;
  height: auto;
}

.textForBottom {
  position: absolute;
  /*new code*/
  bottom: 0;
}
<div class="mainContainer">
  <div class="subContainer">
    <img src="https://static01.nyt.com/images/2021/09/14/science/07CAT-STRIPES/07CAT-STRIPES-mediumSquareAt3X-v2.jpg" alt="cat" />
    <div class="anotherDiv">
      <span class="textForBottom">
      This text should be at the bottom in the div that contains it
      </span>
    </div>
  </div>
</div>

Upvotes: 1

Zach Jensz
Zach Jensz

Reputation: 4078

Here's a grid solution:

* {
  box-sizing: border-box;
}

html,
body {
  padding: 0;
  height: 100%;
}

.mainContainer {
  display: grid;
  place-items: center;
  height: 100%;
}

.subContainer {
  display: grid;
  grid-template-columns: 20% 80%;
  width: 60%;
}

.anotherDiv {
  display: grid;
  grid-template-rows: 1fr auto;
  background-color: rgb(195 171 171);
}

img {
  width: 100%;
  height: auto;
}

.textForBottom {
  grid-row: 2 / 3;
}
<div class="mainContainer">
  <div class="subContainer">
    <img src="https://static01.nyt.com/images/2021/09/14/science/07CAT-STRIPES/07CAT-STRIPES-mediumSquareAt3X-v2.jpg" alt="cat" />
    <div class="anotherDiv">
      <span class="textForBottom">
         This text should be at the bottom in the div that contains it
      </span>
    </div>
  </div>
</div>

Upvotes: 1

Related Questions