Search code examples
htmlcsscss-position

News items stack in top of each other with CSS position


I'm trying to create a webpage that has news items in a way that it has news image, image overlay, headline and text all in top of each other. However with my code, if I try to continue to create next news below copying everything, it will stack in top of the first news. So how can I get the next similar "News2" image+image+headline+text combo appear under the "News1" instead of overlapping?

I could use "top: xxx px;" to force News2 items down, but it seems like a bad solution when there will be lots of news items in a page.

HTML:

<div class="NewsImage1 NewsImageBig"><img src="image.jpg" class="NewsImageBig"></div>
<div class="NewsImageOverlay1 NewsImageBig"><img src="Gfx/imageoverlay.png" class="NewsImageBig"></div>
<div class="NewsImageHeadline1">News headline goes here</div>
<div class="NewsImageText1">News text goes here</div>

CSS:

.NewsImageBig {
    position: absolute;
    max-width: 850px;
    max-height: 283px;
    border-radius: 10px;
    margin: 0px 12px;
}
.News1 {
    position: relative;
}
.NewsImage1 {
    z-index: 0;
}   
.NewsImageOverlay1 {
    z-index: 1;
    opacity: 0.9;
}
.NewsImageHeadline1 {
    position: relative;
    top: 215px;
    margin: 0px 45px;
    font-size: 22px;
    z-index: 2;
}
.NewsImageText1 {
    position: relative;
    top: 220px;
    margin: 0px 45px;
    font-size: 14px;
    z-index: 3;
}

Example of webpage when there's only code mentioned here and when I try to duplicate the news item.

Example


Solution

  • An example about the absolute and relative relation. Here both .shadow and .title are position: absolute, only when set to a position: relative container it keeps the normal flow

    .news {
      display: inline-block;
      position: relative;
      background-size: cover;
      width: 40%;
      padding-bottom: 25%;
      border-radius: 10px;
      overflow: hidden;
      margin: 5px;
      box-shadow: 0 1px 7px rgba(0,0,0,.2);
    }
    
    .news .shadow {
      position: absolute;
      z-index: 1;
      top:0; left: 0; right: 0; bottom: 0;
      background: -webkit-linear-gradient(top, rgba(0,0,0,0) 50%, rgba(0,0,0,1) 100%);
    }
    .news .title {
      color: #FFF;
      position: absolute;
      z-index: 2;
      bottom: 5%; left: 5%; right: 5%;
    }
    .news .title h2, .news .title p {
      margin: 5px 0;
    }
      <div class="news" style="background-image: url(https://picsum.photos/200);">
        <div class="shadow"></div>
        <div class="title">
          <h2>Title</h2>
          <p>lorem ipsum dolor sit emet</p>    
        </div>
      </div>
    
      <div class="news" style="background-image: url(https://picsum.photos/200);">
        <div class="shadow"></div>
        <div class="title">
          <h2>Title</h2>
          <p>lorem ipsum dolor sit emet</p>    
        </div>
      </div>