要使div水平居中,您可以使用margin: auto auto; width: 500px宽度为您想要的任何宽度的位置.
HTML:
<div id="content">
Some content
</div>
Run Code Online (Sandbox Code Playgroud)
CSS:
#content {
width: 200px;
margin: auto auto;
background-color: #CCC;
}
Run Code Online (Sandbox Code Playgroud)
如果你可以修复内容的高度和宽度,那么只需使用css就可以水平和垂直居中.这是通过将您的内容包装在另一个div中,然后定位内容div top: 50%,然后从其中减去其边距的一半来实现的:margin-top: -100px假设高度为200px.见下面的例子:
HTML:
<div id="wrapper">
<div id="content">
Some content
</div>
</div>
Run Code Online (Sandbox Code Playgroud)
CSS:
#wrapper {
position: relative;
background-color: #EEE;
width: 200px;
height: 200px;
font-size: 10px;
}
#content {
position: absolute;
top: 50%;
left: 50%;
width: 80px;
height: 80px;
margin-top: -40px;
margin-left: -40px;
background-color: #DDD;
}
Run Code Online (Sandbox Code Playgroud)
此外,您可以在大多数台式机和笔记本电脑屏幕上使用固定margin-top(或top使用position: absolute)使其看起来垂直居中.
HTML:
<div id="content">
Some content
</div>
Run Code Online (Sandbox Code Playgroud)
CSS:
#content {
width: 200px;
margin: 100px auto;
background-color: #CCC;
}
Run Code Online (Sandbox Code Playgroud)
仅使用css不可能以任意高度垂直居中内容.在这种情况下,您将需要使用Javascript来定位div:
基本思路是:
我个人的偏好是您使用position: absolute与top属性.您也可以使用,margin-top但如果您在页面上有其他内容,则可能不希望此div占用框模型中的空间.
<html>
<head>
<script src="http://code.jquery.com/jquery-1.9.1.min.js"></script>
<script type="text/javascript">
$(function() {
var windowWidth = document.documentElement.clientWidth;
var windowHeight = document.documentElement.clientHeight;
var el = $('#content');
var elWidth = el.width();
var elHeight = el.height();
el.css({
position: 'absolute',
top: (windowHeight / 2) - (elHeight / 2),
left: (windowWidth / 2) - (elWidth / 2),
});
});
</script>
<style>
#content {
width: 200px;
height: 200px;
background-color: #CCC;
}
</style>
</head>
<body>
<div id="content">
Some content
</div>
</body>
</html>
Run Code Online (Sandbox Code Playgroud)
Web上有许多CSS框架,它们提供我们在大多数网站上使用的样板CSS.其中一些也有助于解决这些小Javascript插件的常见问题.就个人而言,我知道Twitter Bootstrap提供了一个Modal插件,您可以将其用于此目的.还有许多jQuery插件,其唯一目的是将页面内容集中在一起.
虽然有很多选项可以实现这一点,但我很遗憾看到CSS仍然不支持这样做.我不知道,在不同的场景中做这件事可能很难.从我上面提到的选项中,我认为Javascript选项是最通用的,并且具有当今的浏览器速度,以及没有人在浏览器上禁用Javascript的可能性,这将是最好的方法.