Search code examples
htmlcsscss-grid

Why did new element down behind the grid images in html?


I'm new to CSS grid and I tried to make this code but I faced a problem which is any new element appeared behind the grid images, I tried to change the position of <h2 class="attachment__title"> to relative and give it z-index with value 1 so it's became above the image, but I need it to be down below the images.

/*==================== Image Grid ====================*/

.grid__title {
  color: #ffcc00;
  text-shadow: 1px 1px #131313;
  margin: 10px;
  text-align: center;
}

.image__grid {
  position: absolute;
  justify-content: center;
  align-items: center;
  margin: 10px 0 auto;
  width: 100vw;
  grid-template-columns: repeat(auto-fill, minmax(300px, 300px));
  column-gap: 10px;
  row-gap: 10px;
}

.image__grid img {
  width: 250px;
  height: 250px;
  object-position: center;
}

.attachment__title {
  color: #ffcc00;
  text-shadow: 1px 1px #131313;
  margin: 10px;
  text-align: center;
  position: relative;
  z-index: 1;
}

.attachment__content {
  margin: 10px;
  text-align: center;
  font-size: 24px;
  display: block;
  position: relative;
  z-index: 999;
}

.attachment__content a {
  text-decoration: none;
  font-weight: 700;
  font-size: 32px;
}
<h2 class="grid__title">Trip Gallery</h2>
<div class="image__grid">
  <img src="img/grid1.jpg" alt="Image 1">
  <img src="img/grid2.jpg" alt="Image 2">
  <img src="img/grid3.jpg" alt="Image 3">
  <img src="img/grid4.jpg" alt="Image 4">
  <img src="img/grid5.jpg" alt="Image 5">
  <img src="img/grid6.jpg" alt="Image 6">
  <img src="img/grid7.jpg" alt="Image 7">
  <img src="img/grid8.jpg" alt="Image 8">
  <img src="img/grid9.jpg" alt="Image 9">
</div>
<!--== PDF ==-->
<div id="test">
  <h2 class="attachment__title">PDF File</h2>
  <p class="attachment__content">Open a PDF file <a href="/uploads/media/default/0001/01/540cb75550adf33f281f29132dddd14fded85bfc.pdf">From Here</a>.</p>
</div>


Solution

  • W3 have a helpful guide on CSS grid settings: https://www.w3schools.com/css/css_positioning.asp

    In your code, the image grid is set to position:absolute; If you try position:relative; the content will be adjusted to fit around other elements. There are five different CSS layout values to try: static, relative, fixed, absolute, and sticky.