Vertically center ul in div

前端 未结 5 1028
忘掉有多难
忘掉有多难 2020-12-10 14:22

This is what my code looks like.

相关标签:
5条回答
  • 2020-12-10 14:53

    You can use flex to make your ul center vertical, horizontal or both like

    .container{
      background:#f00;
      height:150px;
      display:flex;
      align-items:center;
      /*justify-content:center;=>will make ul center horizontal*/
    }
    .container ul{
      background:#00f;
    }
    <div class="container">
      <ul>
        <li>A</li>
        <li>B</li>
        <li>C</li>
      </ul>
    </div>

    0 讨论(0)
  • 2020-12-10 15:03

    If you can add jQuery library you could try this,

    $(document).ready(function(){
    
        // Remove li float
        $("#container ul li").css("float", "none");
    
        // Get the full height of the UL
        var ulheight = $("#container ul li")[0].scrollHeight;
    
        // Based on the height of the container being 50px you can position the UL accordingly
        var pushdown = (50-ulheight)/2;
        $("#container ul li").css("top", pushdown);
    
    });
    
    0 讨论(0)
  • 2020-12-10 15:03

    Now you can make the parent container display:flex and align-items:center. That should work. Although flexbox properties are not supported by older browsers.

    0 讨论(0)
  • 2020-12-10 15:05

    Please use the search function in the future. The full answer is explained here; this is the code for your scenario:

    .container {
      display: table;
      height: 100%;
      position: absolute;
      overflow: hidden;
      width: 100%;}
    .helper {
      #position: absolute; /*a variation of an "lte ie7" hack*/
      #top: 50%;
      display: table-cell;
      vertical-align: middle;}
    ul{
      #position: relative;
      #top: -50%;
      margin:0 auto;
      width:200px;}
    

    The three elements have to be nested like so:

    <div class="container">
      <div class="helper">
        <ul><!--stuff--></ul>
      </div>
    </div>
    

    http://jsfiddle.net/ovfiddle/yVAW9/

    0 讨论(0)
  • 2020-12-10 15:07

    "Centring" a div or other containers vertically is quite tricky in CSS, here are your options.

    You know the height of your container

    If you know the height of the container, you can do the following:

    #container {
        position: absolute;
        top: 50%;
        margin-top: -half_of_container_height_here;
    }
    

    So we essentially place in the middle and then offset it using a negative margin equal to the half of the height. You parent container needs to have position: relative.

    You don't know the exact height of your container

    In this case you need to use JavaScript and calculate the appropriate margins (unfortunately you cannot use margin-top: auto or something similar).

    More info here.

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