CSS responsive horizontal centering

14,342

Solution 1

 #logo {margin-right:auto; margin-left:auto; width:500px; height:100px;}

Solution 2

#logo { height:100px; margin:0 auto; width:500px; }

This is the standard way of centering an image by telling it to automatically determine the space on both the left and right of a fixed size container.

And an example.

Solution 3

I guess it depends on how you define "responsive", but if you mean responsive in the sense that content resizes to accomodate the width of the viewport, then all of the other answers don't meet this criteria since they rely on fixed pixel widths. For example, what happens if the view port is less than 500px?

A similar concept will work with percent widths, and actually be responsive, in that the thing you're centering will be flexible too:

#container { width:100%; height:100%; position:fixed; left:0; right:0; z-index:100;}
#logo { position:fixed; width:80%; z-index:101; left:50%; margin: 10% auto auto -40%;}

If you don't want the "logo" element to get to big (on huge screens), you can add max-width:600px; to limit it, but you'd need to add some media-queries to keep it properly centered on large screens.

Share:
14,342
alexandru
Author by

alexandru

Updated on June 15, 2022

Comments

  • alexandru
    alexandru about 2 years

    I was trying to horizontally center an image (logo) for every screen size doing something like this

    #container {position:relative width:100%; height:100%;}    
    #logo {position:absolute; top:0; left:50% width:500px; height:100px;}
    

    and it's not working. Do I maybe have to use a width for container in pixels?