Search code examples
htmlcssimagecentering

Center a combination of text and image within a DIV


I try to center (both horizontally and vertically) a concatenation of a text and an image within a container DIV. Here is the code:

<!DOCTYPE html>
<html>
  <head>
    <style>
      #myBox {display:block; width:300px; height:100px;
              text-align:center; font-size:20px; line-height:500%;
              background-color:yellow;}
      #myImg {display:block; width:33.33%; height:100%;}
    </style>
  </head>
  <body>
    <div id="myBox">
      My text
      <img id="myImg" src="red100x100.jpg" />
    </div>
  </body>
</html>

The text is indeed centered, but the image appears in a new line.

Trying to achieve this:
enter image description here

But I get this:
enter image description here

EDIT:

This is similar to center image next to two lines of text responsively , but the latter also deals with effect of margin:auto, while this question does not.


Solution

  • 1) use of display:inline-block; for #myImg.

    2) use of vertical-align: middle; for put text in center Vertically.

    #myImg {
        display:inline-block;
        vertical-align: middle;
        //Other code...
    }
    

    #myBox {
      display:block;
      width:300px;
      height:100px;
      text-align:center;
      font-size:20px;
      background-color:yellow;
    }
    
    #myImg {
      display:inline-block;
      width:33.33%;
      height:100%;
      vertical-align: middle;
    }
    <div id="myBox">
      My text
      <img id="myImg" src="https://encrypted-tbn0.gstatic.com/images?q=tbn:ANd9GcQEnn9dYYZlciBKfaHCw17-dUgRPX3nq5_6-kV1ua-LIsId5g43uA" />
    </div>