I’d like to center a container <div> tag on a page so that it satisfies the following conditions:
- When the screen width is greater than the
<div>‘s max width, I’d like the<div>to be horizontally centered within the screen. - When the screen width is equal to the
<div>‘s max width, the<div>should fill the entire screen. - When the screen width is smaller than the
<div>‘s max width, the<div>should resize to match the width of the screen.
Is this possible with CSS only, or will I need to use JavaScript to accomplish this kind of flexibility?
It’s very possible.
How?
The key here is the CSS
max-widthproperty, as well asmargin: 0 auto;for centering.Here’s a rather-well-commented jsFiddle: little link.
HTML:
CSS:
As @Cerbrus mentioned in comments,
margin: 0 auto;actually setsmargin-topas well. So if you’re willing to have a different value formargin-top, use the following instead: