Why can’t I center image using text-align:center?

Asked

Viewed 1,336 times

14

Follow the code below:

HTML

<div class="panel panel-default" style="height:400px">
  <div class="panel-body">
    <div class="form-group">
      <div class="col-xs-6">
      </div>
    </div>
    <img id="image" width="300" src="http://cdn.arstechnica.net/wp-content/uploads/2016/02/5718897981_10faa45ac3_b-640x624.jpg">
  </div>
</div>

CSS

    #image {
    text-align:center;
}

Here is an example in jsfiddle

Commanding <center></center> works, but many people do not recommend.

  • 1

    It makes no sense to apply align to the image. apply to div from outside of it.

  • Truth @Bacco, thanks, solved my problem.

  • 1

    The problem was applying aling on the image, but now it has been solved

3 answers

11


The problem is that you are trying to center the content of the image. To work the text-align:center, it would have to be applied to div where the image is. But it is also not the way.

The best is to set the image with display:block and place automatic margin:

#image {
  display:block;
  margin:0 auto;
}
<div class="panel panel-default" style="height:400px">
  <div class="panel-body">
    <div class="form-group">
      <div class="col-xs-6">
      </div>
    </div>
    <img id="image" width="300" src="http://cdn.arstechnica.net/wp-content/uploads/2016/02/5718897981_10faa45ac3_b-640x624.jpg">
  </div>
</div>

(despite common sense, the image is usually implemented as inline-block and not as block)

6

You need to apply the text-align in the div panel-body and not in the picture.

4

#image {  
  display: table;
  margin-left:auto;
  margin-right:auto;
}
<div class="panel panel-default" style="width:500px; border:1px solid">
  <div class="panel-body">
    <div class="form-group">
      <div class="col-xs-6">
      
      </div>
    </div>
    <img id="image" width="300" src="http://cdn.arstechnica.net/wp-content/uploads/2016/02/5718897981_10faa45ac3_b-640x624.jpg">
  </div>
</div>

Browser other questions tagged

You are not signed in. Login or sign up in order to post.