Vertical space on elements with position:absolute

前端 未结 3 720
名媛妹妹
名媛妹妹 2021-02-19 02:43

How can I make elements with position:absolute and dynamic height occupy vertical space using only css? Is there any trick with containers and disp

相关标签:
3条回答
  • 2021-02-19 02:59

    position: absolute means they don't occupy space in the flow. However, you don't have to animate using margin, you can use float to let the elements take up whatever space, and make each of the elements position:relative.

    div.animate-me {
       width: 300px;
       margin: 20px;
       float: left;
       left: -1000px; // Make them start offscreen
       position: relative;
       border: 1px solid red;
       visibility: hidden
    }​
    
    $('div').css().animate({
        left: 0
    });
    

    SAMPLE http://jsfiddle.net/qxzzX/1/

    0 讨论(0)
  • 2021-02-19 03:14

    This doesn't apply to all situations, but: if the position: absolute element has a fixed aspect ratio (e.g. an image or video resizing responsively with height: auto), you can take advantage of the padding-bottom trick to give a spacer element that same aspect ratio, so that it resizes in tandem with the absolute element:

    .spacer {
      height: 0;
      padding-bottom: 125%; /* for a 1.25 height/width ratio */
    }
    

    You can read the link, but this works because padding-bottom with a percentage is interpreted as a percentage of the element's width.

    It's then up to your particular layout to position the spacer such that it precisely covers or underlays the position: absolute element, and takes up the space that your absolute element would have were it not absolute.

    0 讨论(0)
  • 2021-02-19 03:23

    Unfortunately, using absolute positioning means, by definition, that your element is no longer taking up space. So no, only through css there is no way to do this.

    You can of course use jQuery (or plain javascript) to accomplish this. How I'd do it is have a space element next to each vertical element. Enclose both the space element and the absolutely positioned vertical element in a relatively positioned div. On page load, change the height of the space element to match the height of the vertical element.

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