0

I'd like to put a div in the center but without place the elements inside the div in the center too. Live example. I want the div itself with border in the center but not its contents (in this case, they should be on right side). How can I do this? I tried with padding, margin but I can't make it working.

Jack
  • 16,276
  • 55
  • 159
  • 284
  • 2
    The div is 100% of the width of it's parent so there's nothing to center. If you don't want the contents centered, remove the `text-align:center`. – j08691 Mar 04 '15 at 21:10
  • Set a width, then set `margin: 0 auto;` – Austin Mullins Mar 04 '15 at 21:11
  • Did you look at [Positioning
    element at center of screen](http://stackoverflow.com/questions/9862167/positioning-div-element-at-center-of-screen)?
    – Tachyon Mar 04 '15 at 21:12

3 Answers3

2

a div is a block element by default, meaning it'll take up 100% of the width of it's parent. If you want to center-align it, you can do so by specifying a (smaller) fixed width then aligning with margin: 0 auto;. This adds an equal amount of margin on each side, making up the rest of the width.

#a {
    border: 2px solid;
    width: 500px;
    margin: 0 auto;
}

Working fiddle: http://jsfiddle.net/yj55ttes/

rmorrin
  • 2,305
  • 1
  • 15
  • 18
1

If div A (or B) has a fixed size when you decide to center it, set the css to this:

#a {
    width:200px;
    border: 2px solid;
    margin:0 auto 0 auto;
}

This will center without using text-align:center;

If you don't have a fixed width, set div B to have text-align:left;

#a {
    border: 2px solid;
    text-align:center;
}
#b {
    text-align:left;
}
Spencer May
  • 4,266
  • 9
  • 28
  • 48
1

Maybe you want to reset inner elements to 'initial' alignment, saying 'left'.

#a {
    border: 2px solid;
    text-align: center;
}
#a * {
    text-align: initial;
}

http://jsfiddle.net/nxp1tb2r/5/

dsuess
  • 5,219
  • 2
  • 22
  • 22