Search code examples
htmlcssbootstrap-4alignment

Centering div with image which uses bootstrap classes


I am trying to center an image on the page, but it only works for mobile screens because I put col-xs-12 for <img> tag. Is there any problem in this class:

col-md-6 col-xs-12 img-responsive text-center

I tried to put margin: 0 auto to <img> and to .pict div, but it doesn't work. Also, I've tried center-block class and text-center.

<div class="container" style="width: 100%">
    <div class="pict" style="width: 100%">
        <div class="img-pict" style="margin: 0 auto">
            <img src="../img/CoverCNVol1No1.png" class="col-md-6 col-xs-12 img-responsive text-center">
        </div>
    </div>
</div>

The image is standing on the left side, it should be at the center of the screen.


Solution

  • The idea is using the bootstrap container classes col-md-6 and alike to size containers for the image for different screen sizes and put the img inside.

    You can convert the image to inline element using display: inline-block; and use the bootstrap text-center class or text-align: center; on the container div.

    Or you can leave the image as is (block element) and center it with margin: auto or bootstrap4 mx-auto on the container div.

    Also have in mind that for horizontal centering you are setting the left and right margins to auto. Top and bottom can still be sized as you need them.

    <div class="container" style="width: 100%;">
      <div class="pict" style="width: 100%;">
        <div style="margin: auto;" class="img-pict col-md-6 col-xs-12">
            <img src="../img/CoverCNVol1No1.png" class="img-responsive" />
        </div>
    </div>