请帮助我将消息框置于适合任何屏幕分辨率的中心位置。 你能展示我可以使用的css或样式,边距,左,右吗?
答案 0 :(得分:8)
要将div水平居中,您可以使用margin: auto auto; width: 500px
,其中宽度是您想要的任何宽度。
HTML:
<div id="content">
Some content
</div>
CSS:
#content {
width: 200px;
margin: auto auto;
background-color: #CCC;
}
如果你可以修复内容的高度和宽度,那么只需使用css就可以水平和垂直居中。这是通过将您的内容包装在另一个div中,然后定位内容div top: 50%
然后从其中减去其边距的一半来实现的:margin-top: -100px
,假设高度为200px。见下面的例子:
HTML:
<div id="wrapper">
<div id="content">
Some content
</div>
</div>
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;
}
此外,您可以提供固定的margin-top
(或top
与position: absolute
),使其在大多数桌面和笔记本电脑屏幕中显示为垂直居中。
HTML:
<div id="content">
Some content
</div>
CSS:
#content {
width: 200px;
margin: 100px auto;
background-color: #CCC;
}
仅使用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>
网络上有许多CSS框架,它们提供我们在大多数网站上使用的样板CSS。其中一些也有助于解决这些小Javascript插件的常见问题。就个人而言,我知道Twitter Bootstrap提供了Modal plugin,您可以将其用于此目的。还有许多jQuery插件,其唯一目的是将内容集中在页面中。
虽然没有了多种选项来实现这一点,我就伤心地看到,CSS仍然不支持这样做。我不知道,在不同的场景中做这件事可能很难。从我上面提到的选项中,我认为Javascript选项是最通用的,并且具有今天的浏览器速度,以及没有人在浏览器上禁用Javascript的可能性,这将是最好的方式。
答案 1 :(得分:2)
我在阅读了有关如何在CSS Techniques页面上进行操作后才看到这一点。
基本上,定义一个小小的CSS:
.Absolute-Center {
margin: auto;
position: absolute;
top: 0; left: 0; bottom: 0; right: 0;
}
跨浏览器(包括IE8-10)
没有特殊标记,最小样式
响应百分比和最小/最大 -
使用一个班级来集中任何内容
我没有时间对它进行测试,但是我想在这里发布它,希望它可以帮助其他人。
答案 2 :(得分:0)
以下是您要搜索的http://tutorialzine.com/2010/03/centering-div-vertically-and-horizontally/
您可以使用jquery轻松制作它!或者使用本网站提供的css解决方案!
答案 3 :(得分:0)
您应该向我们提供您尝试过的代码。假设您有以下HTML代码:
<div id="message">
Hello World!
</div>
CSS代码:
#message {
width: 100px;
height: 100px;
margin: 50px auto;
}
然后您的消息框将从屏幕顶部100x100和50px自动对齐到屏幕中心。