How do I position one image on top of another in HTML?

前端 未结 10 1364
难免孤独
难免孤独 2020-11-22 17:15

I\'m a beginner at rails programming, attempting to show many images on a page. Some images are to lay on top of others. To make it simple, say I want a blue square, with

相关标签:
10条回答
  • 2020-11-22 17:41

    Create a relative div that is placed in the flow of the page; place the base image first as relative so that the div knows how big it should be; place the overlays as absolutes relative to the upper left of the first image. The trick is to get the relatives and absolutes correct.

    0 讨论(0)
  • 2020-11-22 17:45

    You can absolutely position pseudo elements relative to their parent element.

    This gives you two extra layers to play with for every element - so positioning one image on top of another becomes easy - with minimal and semantic markup (no empty divs etc).

    markup:

    <div class="overlap"></div>
    

    css:

    .overlap
    {
        width: 100px;
        height: 100px;
        position: relative;
        background-color: blue;
    }
    .overlap:after
    {
        content: '';
        position: absolute;
        width: 20px;
        height: 20px;
        top: 5px;
        left: 5px;
        background-color: red;
    }
    

    Here's a LIVE DEMO

    0 讨论(0)
  • 2020-11-22 17:45

    It may be a little late but for this you can do:

    HTML

    <!-- html -->
    <div class="images-wrapper">
      <img src="images/1" alt="image 1" />
      <img src="images/2" alt="image 2" />
      <img src="images/3" alt="image 3" />
      <img src="images/4" alt="image 4" />
    </div>
    

    SASS

    // In _extra.scss
    $maxImagesNumber: 5;
    
    .images-wrapper {
      img {
        position: absolute;
        padding: 5px;
        border: solid black 1px;
      }
    
      @for $i from $maxImagesNumber through 1 {
        :nth-child(#{ $i }) {
          z-index: #{ $maxImagesNumber - ($i - 1) };
          left: #{ ($i - 1) * 30 }px;
        }
      }
    }
    
    0 讨论(0)
  • 2020-11-22 17:46

    This is a barebones look at what I've done to float one image over another.

    img {
      position: absolute;
      top: 25px;
      left: 25px;
    }
    .imgA1 {
      z-index: 1;
    }
    .imgB1 {
      z-index: 3;
    }
    <img class="imgA1" src="https://placehold.it/200/333333">
    <img class="imgB1" src="https://placehold.it/100">

    Source

    0 讨论(0)
提交回复
热议问题