Reputation: 87
I'm trying to center my content div. It's set to 100%, and the div is contained in body, which is also set to 100%. I have a max-width: 1400px because I don't want my content to stretch more than that if the screen resolution is higher. The thing is, it doesn't work using margin: auto. My content stands on the left, uncentered on screen wider than 1400px.
If I delete the max-width, everything is perfectly centered on wide screens, but the content is stretched to the the whole screen...
#content {
width: 100%;
height: auto;
position: absolute;
top: 400px;
margin: 0 auto;
margin-top: 50px;
display: none;
max-width: 1400px;
}
Upvotes: 3
Views: 7182
Reputation: 9583
Easiest way to achieve this, is to set the width
property to the max width you need, and add max-width: 100%;
. This will prevent it from being bigger than 100% but still go up to the max width. Also, you should remove the absolute
positioning:
Upvotes: 8
Reputation: 785
You can use the transform
technique, which doesn't require extra mark-up or media queries.
#content {
position: relative; /* 'fixed' will work also. */
max-width: 500px; /* Your required width here. */
width: 100%;
left: 50%;
transform: translateX(-50%);
}
Here's a demo https://jsfiddle.net/matharden/6uduf7av/
Upvotes: 4
Reputation: 1499
Use Flexbox...
Put this classes in the parent element (the body):
The HTML
<body class="p-flexbox flex-hcc">
<!-- The content -->
</body>
Where:
The CSS
.p-flexbox {
display: -webkit-box;
display: -moz-box;
display: box;
}
.flex-hcc {
-webkit-box-orient: horizontal;
-webkit-box-pack: center;
-webkit-box-align: center;
-moz-box-orient: horizontal;
-moz-box-pack: center;
-moz-box-align: center;
box-orient: horizontal;
box-pack: center;
box-align: center;
}
Cheers, Leonardo
Upvotes: 0