CSS: Why “vertical-align: middle” does not work?

前端 未结 8 1064
无人及你
无人及你 2021-02-13 06:24

Consider the following example: (live demo here)

HTML:



        
相关标签:
8条回答
  • 2021-02-13 06:44

    Try using a background image on an <a>:

    <a href="#"></a>    
    a {display:block;background:#000;line-height:40px;background:#000 url(http://img.brothersoft.com/icon/softimage/s/smiley.s_challenge-131939.jpeg) no-repeat left center;text-indent:-999px}
    
    0 讨论(0)
  • 2021-02-13 06:54

    If you know the vertical size of the element and the line height, then you can vertically center it by using vertical-align: top plus a top margin.

    For illustration, I created: http://jsfiddle.net/feklee/cXUnT/30/

    0 讨论(0)
  • 2021-02-13 06:57

    I can't really tell you the specifics as to why this happens (I'm curious myself). But this works for me:

    a {
        display: block;
        background: #000;
        line-height: 40px;  
    }
    img {
        vertical-align: middle;
        margin-top:-4px; /* this work for me with any given line-height or img height */
    }
    
    0 讨论(0)
  • 2021-02-13 07:00

    Just put the img tag inside a div tag the set display:table-cell vertical-align: middle to the div. Parent tag should be display:table

    Example:

    Css

    a {
     display: table;
     background: #000;
     height:200px;
    }
    div {
     display:table-cell;
     vertical-align: middle;
    }
    

    HTML

    <a>
     <div>
      <img src="http://img.brothersoft.com/icon/softimage/s/smiley.s_challenge-  131939.jpeg" />
     </div>
    </a>
    
    0 讨论(0)
  • 2021-02-13 07:05

    You can use position:absolute; for this.

    For example:

    a {
        display: block;
        background: #000;
        line-height: 40px;
        height:80px;
        position:relative;  
    }
    
    img {
        position:absolute;
        top:50%;
        margin-top:-16px;
    }
    

    NOTE: This gives margin-top half of the image size.

    Check this http://jsfiddle.net/cXUnT/7/

    0 讨论(0)
  • 2021-02-13 07:06

    You should have display: table-cell I think, this works only in tables.. I use line-height equal to height of the element and it works too.

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