charliesd
charliesd

Reputation: 123

How to center an image?

I struggled for some time with this issue. My landscape images looked great but I couldn't get my portrait orientated images to align properly. This is the code I had and the auto margin and padding seemed to have no effect at all and the image would always align to the left of the slider (parent element).

.slider img#portrait { 
        min-height: 100%; 
        width: auto; 
        margin: 0 auto;
        padding: 0 auto;
        }

Upvotes: 1

Views: 69

Answers (1)

charliesd
charliesd

Reputation: 123

I managed to find little snippets of what might solve the problem from different sources so I wanted to include all of the ones I used here in one place.

This is now what I have which works well:

.slider img#portrait { 
        height: auto; 
        width: 50%; 
        display: block;
        float: none;
        position: relative;
        margin: 0 auto;
        padding: 0 auto;
        }

Images are by default displayed as inline-block elements. So change this to display: block;

If there is a float: left; then the rulemargin: auto; will have no effect either, so set float: none;

The margin auto will have no effect either unless the image has a set width so width: 50%;

And don't forget to set position: relative;

If you are not modifying the display property of images then you can use: .slider {text-align: center;}. (Only works if applied to parent element.)

Upvotes: 4

Related Questions