LostPhysx
LostPhysx

Reputation: 3641

How to center a div with a relative width?

I have a <div> which is styled as following:

.content{
    width: 70%;
}

To center a div, there is the possibility to set the margin to auto (margin: 0 auto;) but this only works if I have a fixed size(e.g. 400px). So how can I center my div with relative width?

Upvotes: 2

Views: 15197

Answers (3)

ghettovoice
ghettovoice

Reputation: 358

margin: 0 auto works as well or you can use display: inline-block on content div and wrap it by div with text-align: center

<div id="one">one</div>
<br /><br />
<div id="wrap">
    <div id="two">two</div>
</div>

Css

#one {
    width: 70%;
    height: 100px;
    background: #ccc;
    margin: 0 auto;
    text-align: center;
}

#wrap { text-align: center; }
#two {
    width: 70%;
    height: 100px;
    background: #ccc;
    display: inline-block;
    text-align: center;

}

http://jsfiddle.net/4KhJL/3/

Upvotes: 1

balexandre
balexandre

Reputation: 75093

using

<body>
  <div class="content">
    <div class="centered"><h1>Hello</h1></div>
  </div>
</body>

and CSS

.content {
  width: 70%;
  background-color: #e5e5e5;
}

.centered {
  width: 150px;
  background-color: #ccc;
  margin: 0 auto;
}

you get this:

enter image description here

Demo on JsBin: http://jsbin.com/iDAZeSi/1/


edited from answer

just add margin: 0 auto; to .content so it looks like

.content {
  width: 70%;
  background-color: #e5e5e5;
  margin: 0 auto;
}

and you will get:

enter image description here

Demo on JsBin: http://jsbin.com/iDAZeSi/2/

Upvotes: 0

Explosion Pills
Explosion Pills

Reputation: 191749

margin: 0 auto will also work for percentage divs. The side margins will be calculated based off the percentage of the width.

http://jsfiddle.net/B32mh/

Upvotes: 6

Related Questions