center image in css

There are few pointers to center an image in CSS.

  • First, make sure that the parent element of the image has its width set.
  • Second, the image should not be wider than its parent element, that’s pretty obvious.

See also:  How To Center A Div Inside A Div Easily

Center and Image in CSS horizontally

Images are the same as divs, you can use the text-align into its parent element but not the margin: 0 auto alone on the image.
To center image in div, set a width of the div then add margin:0 auto and display: block into the image in CSS.

The HTML code:

<div class="wrapper"><img src="http://22bulbjungle.com/wp-content/uploads/2017/04/rabbit_in_hand.jpg" /></div>

 

The CSS styles:

.wrapper{
width: 100%;
height: 300px;
border: 2px solid #93c504;
}
img{
max-width: 250px;
display: block;
margin: 0 auto
}

This will result into an image centered horizontally:

center-image_margin_0_auto

 

See the jsfiddle:

Make sure you have a smaller image width than the parent element.

The margin’s first value 0 was for the top and bottom margin. While the second is for left and right margin.

You can also set margin-left: auto and margin-right: auto on the image in CSS.

Center an Image in CSS horizontally and vertically

We will going to use the span element to guide our image  making it center. Setting an image with margin and text-alignment could not make our image center align.

The HTML code:

<div class="wrapper"><img src="http://22bulbjungle.com/wp-content/uploads/2017/04/rabbit_in_hand.jpg" /></div>

The CSS styles:

.wrapper {
width: 100%;
height: 300px;
border: 2px solid #93c504;
text-align: center
}

.for-image {
height: 100%;
display: inline-block;
vertical-align: middle
}

img {
max-width: 200px;
height: auto;
background: #3A6F9A;
vertical-align: middle
}

center-image_margin_auto

Responsive design images

Creating a responsive design image is very useful for mobile devices.

Responsive image will automatically scale down and adjust to the width of the device.

To create a responsive design image, you just set a max-width: 100%; and height: auto; into the images.

The max-width: 100%; means the image’s width will cover all its parent’s width. You can also set a natural image width(full resolution width of the image) to the max-width property so it will not be basing upon its parent element’s width.

The height: auto; makes the image height and width proportional. As a result, it would not stretch.

What happens if you will not set a height: auto; is, the image’s original height will still be the same while the width is scaling according to the device’s width, so it will be non-proportional.