How to vertically align both image and text in a DIV using CSS?

后端 未结 2 1680
半阙折子戏
半阙折子戏 2020-12-04 12:24

I have an image and some text inside a div and I\'d like to put the image and the text in the vertical center of the div using CSS. The problem is that I don\'t know how man

相关标签:
2条回答
  • 2020-12-04 12:57

    Give both the image and the text a vertical-align: middle - the text needs to be contained in an element that is also display: inline. So markup like this:

    <div>
      <span><img src="blah.jpg" /></span>
      <span>text text text</span>
    </div>
    
    div {
      display: table;
    }
    
    img {
      vertical-align: middle;
      display: table-cell;
    }
    span {
      vertical-align: middle;
      display: table-cell;
    }
    

    should work. Here's a jsfiddle to demonstrate (edited fiddle to show everything is vertically aligned within a container as well.)

    EDIT: to get the behavior you want, I recommend using additional display properties - table for the container and table-cell for the contained elements. Fiddle link has been updated with the changes.

    EDIT: the only way I could think of to get it to work was to wrap the image in another inline container, in this case a span. I've updated the fiddle to demonstrate.

    0 讨论(0)
  • 2020-12-04 13:06

    You may try this, example here.

    CSS:

    div.parent{ 
        border:solid black 1px;
        display:table;
        padding:5px; 
        width:100%;
        margin:5px 0; /* you can change/remove margin */
    }
    div.text{ 
        vertical-align:middle;
        display:table-cell;
        text-align:justify;
    }
    div.parent .img{
        vertical-align:middle;
        display:table-cell;
        padding-right:5px;
        width:50px; /* you can change width */
    }
    div.img img{ 
        width:100%;
        height:50px; /* you can change height */
        vertical-align:middle;
    }
    

    ​HTML:

    <div class="parent">
        <div class="img"><img src="http://example.com.img1.png" /></div>
        <div class="text">Some Text Some.</div>
    </div>
    
    0 讨论(0)
提交回复
热议问题