Xavier
Xavier

Reputation: 87

Centering fluid div having max-width

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

Answers (3)

Derek Story
Derek Story

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:

JS Fiddle

Upvotes: 8

matharden
matharden

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

leoMestizo
leoMestizo

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:

  1. p-flexbox means parent-flexbox
  2. flex-hcc means flexbox-horizontal-center-center

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

Related Questions