Evenly distribute images vertically within fixed-height space

后端 未结 2 1633
心在旅途
心在旅途 2020-12-30 14:29

I have 3 images vertically aligned in fixed height div. How can I make sure that the top and bottom padding between them remains even when an image is added or deleted.

相关标签:
2条回答
  • 2020-12-30 14:47

    I know I'm bound to stumble across this again the next time I search for it. Leaving this as a reference for myself. Difference is elements don't have to have fixed heights per-se:

    http://codepen.io/anon/pen/ojBPaq?editors=110

    HTML

    <ul>
      <li><div class="tile-wrap one"><div class="tile">wefwfwefww efwefwfwfewfwef wefwfwf wefwfe wefwf wefwfwfwfwf wef wefwfe</div></div></li>
      <li><div class="tile-wrap two"><div class="tile"></div></div></li>
      <li><div class="tile-wrap three"><div class="tile"></div></div></li>
    </ul>
    

    CSS

    * { box-sizing: border-box; }
    
    ul {
      list-style: none;
      margin: 0;
      padding: 0;
      background: grey;
      width: 500px;
      height: 400px;
      display: table;
    }
    
    li {
      display: table-row;
      background: aqua;
      vertical-align: bottom;
    }
    
    .tile-wrap {
      display: table-cell;
      vertical-align: middle;
    }
    
    .one {
      vertical-align: top;
    }
    
    .two {
      vertical-align: middle;
    }
    
    .three {
      vertical-align: bottom;
    }
    
    .tile-wrap .tile {
      width: 100px;
      min-height: 100px;
      background: white;
      border: 1px solid blue;
    
    }
    
    0 讨论(0)
  • 2020-12-30 14:49

    You want to:

    1. set the div to display:table with a fixed height,
    2. wrap each <img> in element with display:table-row and display:table-cell
    3. set the images to display:block
    4. set the table-cell elements to vertical-align:middle
    5. set the height of the first and last rows to be exactly as tall as the images themselves

    This will cause the space to be evenly distributed vertically.

    Demo: http://jsfiddle.net/X2URZ/2/

    Code:

    <ul id="img-list">
      <li><span><img src="http://phrogz.net/tmp/gkhead.jpg"></span></li>
      <li><span><img src="http://phrogz.net/tmp/gkhead.jpg"></span></li>
      <li><span><img src="http://phrogz.net/tmp/gkhead.jpg"></span></li>
    </ul>​
    
    #img-list { display:table; height:100px }
    #img-list img { height:20px; display:block }
    #img-list li { display:table-row }
    #img-list li span { display:table-cell; vertical-align:middle; background:red }
    #img-list li:first-child,
    #img-list li:last-child { height:20px }​
    
    0 讨论(0)
提交回复
热议问题