How to center a fixed element with CSS.

How to center a fixed element with CSS.

In the middle of making a certain website, I wanted the logo image to be vertically and horizontally centered in the middle of the screen. In terms of the CSS knowledge I had, I decided to give it the following styles:

.logoImage {
    position: fixed;//can be absolute
    top: 50%;
    left: 50%:
}

What the following styles actually accomplish is putting the upper left corner of the image exactly in the center of the page, not the center of the image in the center of the page.

The Trick

In order to exactly center the image, you've to apply a negative top margin of half the images height, and a negative left margin of half the images width.

Hence the correct code should be:

//image height = 100px;
//image width = 200px;

.logoImage {
    position: fixed;
    top: 50%;
    left: 50%;
    marigin-top: -50px;
    margin-bottom: -100px;
}

This works perfectly if you're able to know the size of the thing you would wish to center.

You can also try the following method:

.logoImage {
    position: fixed;
    top: 50%;
    left: 50%:
    transform: translate(-50%, -50%); 
}

The translate value for transform is based off the size of the element.

Hope it works!!!!!!!!!!