Why can not I center image using 'text-align: center'? [duplicate]

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'sanexampleat jsfiddle

With <center></center> command works, most people do not recommend it.

    
asked by anonymous 30.12.2016 / 00:30

3 answers

11

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

It is best to set the image with display:block and set auto 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 block )

    
30.12.2016 / 00:35
6

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

    
30.12.2016 / 00:34
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>
    
30.12.2016 / 00:38