CSS vertically align floating divs

后端 未结 6 2127
终归单人心
终归单人心 2020-12-04 10:48

I have a div (#wrapper) containing 2 divs standing side by side.

I would like the right-div to be vertically aligned. I tried vertical-align:middle on my main wrapp

6条回答
  •  日久生厌
    2020-12-04 11:02

    You have no luck with floated elements. They don't obey vertical-align,

    you need, display:inline-block instead:

    http://cssdesk.com/2VMg8

    BEWARE


    Be careful with display: inline-block; as it interpretes the white-space between the elements as real white-space. It does not ignores it like display: block does.

    I recommend this:

    Set the font-size of the containing element to 0 (zero) and reset the font-size to your needed value in the elements like so

    ul {
        margin: 0;
        padding: 0;
        list-style: none;
        font-size: 0;
    }
    ul > li {
        font-size: 12px;
    }
    

    See a demonstration here: http://codepen.io/HerrSerker/pen/mslay


    CSS

    #wrapper{
      width:400px;
      height:auto;
      border:1px solid green;
      vertical-align: middle;
      font-size: 0;
    }
    
    #left-div{
      width:40px;
      border:1px solid blue;
      display: inline-block;
      font-size: initial;
      /* IE 7 hack */
      *zoom:1;
      *display: inline;
      vertical-align: middle;
    }
    
    #right-div{
      width:336px;
      border:1px solid red;
      display: inline-block;  
      font-size: initial;
      /* IE 7 hack */
      *zoom:1;
      *display: inline;
      vertical-align: middle;
    }
      
    

提交回复
热议问题