How do I center a <div>? [duplicate]

和自甴很熟 提交于 2019-12-30 17:45:22

问题


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; or position: 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 like margin: 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 be font-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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!