Jump to content

  • Free consultations and support
  • Live chatClick Here for Live Chat
  • Call ico 1888-906-1888
    Phone support: Open

    Ready for your call :)

    Our business hours:

    Mon — Fri, 2am — 8pm (EST)

    US & EU support teams

    Phone support: Closed

    We are back in: 1h 20m

    Our business hours:

    Mon — Fri, 2am — 8pm (EST)

    US & EU support teams


Centering an Image in CSS

centering image css

  • Please log in to reply
&nsbp;

#1 Ammar11

Ammar11

    Senior Member

  • Designer
  • 197 posts

Posted 04 April 2013 - 02:07 AM

To center an image in CSS do the following:
1 . The image selector is img. Don’t use that selector alone so that not all images on your page become centered. Use a specific selector to center one single image or to center a group of images. Choose a selector that is aimed at only images you want centered.
3. Make the img as a block level element.
Ex.
#sidebar .preview img
{
display: block;
}
4.Add the margins rules for centring the image.
#sidebar .preview img {
display: block;
margin-left: auto;
margin-right: auto;
}

#2 varlan

varlan

    Junior Member

  • Designer
  • 4 posts

Posted 16 April 2013 - 10:52 AM

Thanks for this. It's been something annoying me lately.

#3 mika

mika

    Junior Member

  • Designer
  • 7 posts

Posted 01 May 2013 - 12:13 PM

Just a quick tip:

If you want to shorten the code use the the shorthand property, so instead of:
#sidebar .preview img {
display: block;
margin-left: auto;
margin-right: auto;
}

you can just have this:

#sidebar .preview img {
display: block;
margin:0 auto;
}

This shorthand property is more useful when you need to use all the four margins (top right bottom left)
so you can specify in just one line all the margins of the element.

Example:

margin:10px 20px 30px 40px;

So with that rule we have an elemnt with:
top margin 10px
right margin 20px
bottom margin 30px
left margin 40px


Great info Ammar11 :)

#4 AhmadRad

AhmadRad

    Junior Member

  • Designer
  • 4 posts

Posted 17 September 2013 - 01:32 AM

Thanks

#5 spidergems

spidergems

    Junior Member

  • Designer
  • 7 posts

Posted 24 April 2018 - 07:17 AM

Hi,

 

With the CSS flex-box, now it is a lot easier to center an image in a container. You don't need to write a huge chunk of code. 

<div class="img-container">
 <img src="https://images.pexels.com/photos/783243/pexels-photo-783243.jpeg?auto=compress&cs=tinysrgb&h=350" alt="" />
</div> 
.img-container {
  width: 800px;
  display: flex;
  justify-content: center;
}

img {
  display: block
  width: 500px;
  height: auto;
}

This is all you need to. You can visit the following link to the code pen to see how the code works

 

https://codepen.io/p...mesh/pen/jxqPNx







Also tagged with one or more of these keywords: centering image, css

0 user(s) are reading this topic

0 members, 0 guests, 0 anonymous users