简体   繁体   English

使用html-css将元素居中

[英]centering an element using html-css

My html page is: 我的html页面是:

<html>
<head>
<title>Hello there</title>
<link href="style.css" type="text/css" rel="stylesheet" />
</head>
<body>
<div id="content">
Hello world
</div>
</body>
</html>

My css file is: 我的css文件是:

html, body{
    width: 100%;
    height: 100%;
}

div#content{
    width: 80%;
    display: block;
    margin: 0 auto;
    height: 90%;
    border: 1px solid red;
}

But the content div is not centered properly. 但是内容div没有正确居中。 I am using IE7 to view this page. 我正在使用IE7来查看此页面。

You should add a <!doctype> to the beginning of your document, also remove the display: block; 您应该在<!doctype>的开头添加<!doctype> ,还删除display: block; from your div selector, a div is by default a block level element so this declaration has no meaning. 从div选择器中,默认情况下div是一个块级元素,因此此声明没有任何意义。 (this won't break the layout, it just makes no sense to tell an already block level element to be block again.) (这不会破坏布局,告诉已经块级的元素再次被阻塞是没有意义的。)

Other than that, your CSS is perfectly fine :) 除此之外,您的CSS非常好:)

HTML: HTML:

<!doctype html>
<html>
<head>
<title>Hello there</title>
<link href="style.css" type="text/css" rel="stylesheet" />
</head>
<body>
<div id="content">
Hello world
</div>
</body>
</html>

CSS: CSS:

html, body{
    width: 100%;
    height: 100%;
}

div#content{
    width: 80%;
    margin: 0 auto;
    height: 90%;
    border: 1px solid red;
}

http://jsfiddle.net/u5w8F/ http://jsfiddle.net/u5w8F/

For IE 7 quirksmode (and IE 6) you can add 对于IE 7 quirksmode(和IE 6),您可以添加

html, body{
    text-align: center;
}
div#content{
    text-align: left;
}

to center the div... (old skool) 使div居中...(老派)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM