Using position:absolute while keeping it inside the document flow

后端 未结 3 632
情话喂你
情话喂你 2021-01-17 11:27

\"enter

It\'s a screenshot from a page currently I\'m building. I\'m trying to make su

3条回答
  •  慢半拍i
    慢半拍i (楼主)
    2021-01-17 12:03

    As @mikel already pointed out, you can't keep an element with position: absolute inside the normal document flow, but you can workaround this problem by simulating it.

    Considering the example below:

    img {
      position: absolute;
    }
    
    Lorem Ipsum is simply dummy text of the printing and typesetting industry

    The element is out of flow, this cause the to be hidden behind it.

    You can wrap the absolute element inside an empty container, then add height and width to container equal to height and width of the absolute element. By doing so, an invisible box is created around the absolute element, which makes it appear as part of the document normal flow.

    If you already know the exact dimensions of the element, you can simulate normal flow using just css:

    div {
      border: 2px dotted grey;
      position: relative;
      width: 300px;
      height: 400px;
    }
    
    img {
      position: absolute;
    }
    Lorem Ipsum is simply dummy text of the printing and typesetting industry

    Else, if you don't know the dimensions of the absolute element upfront you have to simulate the normal flow dynamically with javascript:

    window.addEventListener('load', function() {
      var div = document.querySelector('div');
      var img = document.querySelector('img');
      var rect = img.getBoundingClientRect();
    
      div.style.height = rect.height + 'px';
      div.style.width = rect.width + 'px';
    });
    div {
      border: 2px dotted grey;
      position: relative;
      max-width: 200px;
    }
    
    img {
      position: absolute;
      width: 100%;
    }
    Lorem Ipsum is simply dummy text of the printing and typesetting industry

提交回复
热议问题