Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Center Image Vertically and Horizontally in Bootstrap Grid

I'm having trouble figuring out how to center an image vertically and horizontally. Essentially I have two rows of images, all have a width of 150 but heights vary.

CSS

.image-center {
  display: inline-block;
  vertical-align: middle;
  position: relative;
}

HTML

<div class="row">
        <div class="col">
            <img class="center-block image-center" width="150" src="imagery/1.png"/>
        </div>
        <div class="col">
            <img class="center-block image-center" width="150" src="imagery/2.png"/>
        </div>            <div class="col">
            <img class="center-block image-center" width="150" src="imagery/3.png"/>
        </div>            <div class="col">
            <img class="center-block image-center" width="150" src="imagery/4.png"/>
        </div>
    </div>

    <div class="row">
        <div class="col">
            <img class="center-block" width="150" src="imagery/5.png"/>
        </div>            <div class="col">
            <img class="center-block" width="150" src="imagery/6.png"/>
        </div>            <div class="col">
            <img class="center-block" width="150" src="imagery/7.png"/>
        </div>            <div class="col">
            <img class="center-block" width="150" src="imagery/8.png"/>
        </div>
    </div>
like image 822
Matthew Avatar asked Aug 06 '18 07:08

Matthew


People also ask

How do I center an image vertically in Bootstrap?

One way to vertically center is to use my-auto . This will center the element within it's flexbox container (The Bootstrap 4 . row is display:flex ). For example, h-100 makes the row full height, and my-auto will vertically center the col-sm-12 column.

How do you horizontally and vertically center a div in Bootstrap 5?

Aligning content to the center of the DIV is very simple in Bootstrap 5, You just have to convert the div into a flex box using d-flex class property and then use the property align-items-center to vertically align the content in the middle of the div.


Video Answer


2 Answers

This CSS will be responsive for any devices. It will center horizontally and vertically.

.col {
    margin: 0;
    position: absolute;
    top: 50%;
    left: 50%;
    transform: translate(-50%, -50%);
}
like image 122
vinoth s Avatar answered Sep 16 '22 12:09

vinoth s


If you're using Bootstrap 4 (it seems you are), you may use flex alignment classes like align-items-center justify-content-center

 <div class="col d-flex align-items-center justify-content-center">

More info: https://getbootstrap.com/docs/4.1/layout/grid/#alignment

like image 27
tius Avatar answered Sep 17 '22 12:09

tius