Reputation: 3641
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
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;
}
Upvotes: 1
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:
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:
Demo on JsBin: http://jsbin.com/iDAZeSi/2/
Upvotes: 0
Reputation: 191749
margin: 0 auto
will also work for percentage divs. The side margins will be calculated based off the percentage of the width.
Upvotes: 6