Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Center fixed div with dynamic width (CSS)

Tags:

html

css

center

I have a div that will have this CSS:

#some_kind_of_popup {     position: fixed;     top: 100px;     min-height: 300px;     width: 90%;     max-width: 900px; } 

Now, how can i make this div centered? I can use margin-left: -450px; left: 50%; but this will only work when the screen is > 900 pixels. After that (when the window is < 900 pixels), it will no longer be centered.

I can of course do this with some kind of js, but is there a "more correct" of doing this with CSS?

like image 806
gubbfett Avatar asked Jun 12 '13 15:06

gubbfett


People also ask

How can you horizontally center a fixed sized element through CSS?

Add CSS. Set the top and left properties to 50% to center the left-top corner of the <div>. Set the margin-top and margin-left properties to the negative half of the height and width of the <div>.

How do I force a div to center?

Simply add text-align center to parent div and set the child div display to inline-block. This will force our div to behave like inline element and therefore subjected text-align center.


1 Answers

You can center a fixed or absolute positioned element setting right and left to 0, and then margin-left & margin-right to auto as if you were centering a static positioned element.

#example {     position: fixed;     /* center the element */     right: 0;     left: 0;     margin-right: auto;     margin-left: auto;     /* give it dimensions */     min-height: 10em;     width: 90%; } 

See this example working on this fiddle.

like image 132
laconbass Avatar answered Sep 28 '22 04:09

laconbass