Alvaro
Alvaro

Reputation: 9662

Center div horizontally with margin (CSS)

How can I center horizontally a div which has margin?

<div id="container">
    <div id="center_me"></div>
</div>


#container{
    position:relative;
    width:100%;
    height:400px;
}

#center_me{
    position:absolute;
    width:100%;
    margin:0 50px;
    max-width:300px;
    height:100%;
    left:50%;
    -webkit-transform:translateX(-50%);
}

I cant use margin:0 auto, as I want the div to have margin; and the left:50% translateX(-50%) technique doesn't consider the margin. I want to preserve the margin fluidly (always center the div and always preserve the same fixed margin) as the window is resized. Am I missing something very obvious?

http://jsfiddle.net/R3yny/

Just Css,thanks.

Upvotes: 4

Views: 14865

Answers (2)

Nick Grealy
Nick Grealy

Reputation: 25864

Is it possible, to simply have the margin on another div, that sits inside #center_me?

<div id="container">
    <div id="center_me">
        <div id="i_have_the_margin"></div>
    </div>
</div>

Then you can use margin:0 auto; on #center_me, like this - http://jsfiddle.net/nickg1/R3yny/3/ (Tested in Opera)

Upvotes: 4

serraosays
serraosays

Reputation: 7869

By definition, if your element is offset from center with a margin it cannot be centered. What it sounds like you want to do it hold an element in a central-ish place on webpage with a responsive design.

The best way to get that done is to use margin widths as percentages, and eyeball your div until it looks like its about where you want it. Check this sample out- it's really simple:

http://codepen.io/staypuftman/pen/oHGAF

CSS:

.hero-text-area-container {
  background: #d6ffd1;
  float: left;
  margin: 0% 30%;
  padding-top: 20em;
  position: relative;
  width: 50%;
}

Upvotes: 0

Related Questions