我开始编写我的第一个网站,并尝试使用网络上的各种方法(最常见的方法是 margin-left:auto;margin-right:auto;)在 CSS 中将容器 id 居中,但它成功了不起作用,我不知道为什么,也不知道我能做些什么(我知道,我可以在 html 文件中制作一个包含三列的表格,但我不想混合搭配表格和 div)
到目前为止,我的代码如下所示:
HTML:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Untitled Document</title>
<link rel="stylesheet" type="text/css" href="css/style.css"/>
</head>
<body>
<div id="content">
hello world!
</div>
</body>
</html>
CSS:
@charset "utf-8";
/* CSS Document */
body {
background-color:#FFF;
}
#content {
width:980px;
background-color:#FCC;
position: absolute;
display:block;
margin-left: auto;
margin-right: auto;
top: 0px;
bottom:0px;
align:center;
}
最佳答案
解决方案 #1:
在 #content
(CSS) 中将 position: absolute;
替换为 position: relative;
。
JSFiddle - DEMO和 Full Screen View
body, html {
background-color:#FFF;
height:100%;
}
#content {
width:980px;
height: 100%;
background-color:#FCC;
position: relative;
display: block;
margin-left: auto;
margin-right: auto;
top: 0px;
bottom:0px;
text-align:center;
}
<div id="content">hello world!</div>
关于 margin: 0 auto;
center to work 的更多信息:
解决方案#2:
添加 left: 50%;
和 margin-left: -490px;
(#content
div 的一半宽度)到 #内容
JSFiddle - DEMO和 Full Screen View
#content {
width: 980px;
background-color: #FCC;
position: absolute;
display: block;
top: 0px;
bottom: 0px;
margin-left: -490px;
left: 50%;
text-align: center;
}
关于CSS容器不会居中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26037464/