问题
Possible Duplicate:
How to center DIV in DIV?
I want to center a <div>
(I'm new to HTML5 and the <center>
tag is no more), and by all means avoid using a table. This is what I've got as CSS for the <div>
in question so far:
#roundedcorner {
-moz-border-radius: 15px;
border-radius: 15px;
background-image: url(file:///Macintosh%20HD/Users/julesmazur/Desktop/TAN3.0/Photos/bodydivbg.png);
width: 960px;
left: 50%;
font-family: Ubuntu;
}
(for anyone curious, Ubuntu courtesy of Google Web Fonts).
回答1:
The typical trick is margin: auto
. It'll center it inside what-ever it's in.
demo
Besides that I have a few comments on your code (since you're a beginner).
left: 50%;
does nothing unless you change the position style, e.g.,position: relative;
orposition: absolute;
- The container the
div
is in needs to be larger than it -- otherwise centering it really doesn't mean anything. This is because styles likemargin: auto
are relative to the parent container, i.e., it needs space. - For Google Web Fonts, make sure you have your
@font-face
with it. Also, use alternatives. Not all browsers support web fonts, and the more control you have: the better. An example would befont-family: Ubuntu, Arial, Sans;
, ordered from most preferred to most likely backups.
回答2:
Don't use left
. This will create a gab in the page on the left side. Instead, use margin: 0 auto
.
<div style="margin:0 auto;width:960px">I'm centered.</div>
回答3:
You can center DOM elements that are absolutely positioned (horizontally and vertically) by using:
div {
position : absolute;
width : 960px;
height : 500px;
left : 50%;
top : 50%;
margin-top : -250px;
margin-left : -480px;
}
Here is a demo: http://jsfiddle.net/KBHjT/
回答4:
<center><div></div></center>
try that
来源:https://stackoverflow.com/questions/8583735/how-do-i-center-a-div