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

杀马特。学长 韩版系。学妹 提交于 2019-12-01 16:06:01

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.

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>

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/

<center><div></div></center>

try that

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