CSS容器不会居中

标签 css containers center

我开始编写我的第一个网站,并尝试使用网络上的各种方法(最常见的方法是 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 - DEMOFull 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 的更多信息:

What, exactly, is needed for margin: 0 auto; to work?

解决方案#2:

添加 left: 50%;margin-left: -490px; (#content div 的一半宽度)到 #内容

JSFiddle - DEMOFull 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/

相关文章:

html - 在 UL 上使用::before 伪元素创建时间线表示

database - 导入时 MS Access 自动编号

audio - 关于多媒体编解码器的概念(容器、格式、编解码器、复用器、解复用器)

css - Bootstrap : Need help to center a button

html - 如何在不包括图标的菜单中将文本居中?

asp.net 中的 Javascript 和 css 缓存

html - 标题中的电话号码不可点击

php - getimagesize 函数无法正常工作

c++ - reference_wrappers 的容器(需要比较运算符?)

css - Div 稍微偏离中心