【发布时间】:2011-07-22 05:40:11
【问题描述】:
我很困惑如何强制我的 div 元素在我的页面上居中(vertically 和 horizontally)(意味着跨浏览器兼容性的一种或多种方式)?
【问题讨论】:
我很困惑如何强制我的 div 元素在我的页面上居中(vertically 和 horizontally)(意味着跨浏览器兼容性的一种或多种方式)?
【问题讨论】:
方法有很多:
CSS
<div style="width:200px;height:100px;position:absolute;left:50%;top:50%;
margin-left:-100px;margin-top:-50px;">
<!–content–>
</div>
2 。将单行文本水平和垂直居中
CSS
<div style="width:400px;height:200px;text-align:center;line-height:200px;">
<!–content–>
</div>
3 .没有特定度量的元素的水平和垂直居中对齐
CSS
<div style="display:table;height:300px;text-align:center;">
<div style="display:table-cell;vertical-align:middle;">
<!–content–>
</div>
</div>
【讨论】:
This blog post 描述了两种使 div 水平和垂直居中的方法。一种只使用 CSS,并且可以使用固定大小的 div;另一个使用 jQuery,可以处理你事先不知道大小的 div。
我在这里复制了博客文章演示中的 CSS 和 jQuery 示例:
CSS
假设你有一个 .classname 类的 div,下面的 css 应该可以工作。
left:50%; top:50%; 将 div 的左上角设置为屏幕中心; margin:-75px 0 0 -135px; 分别将其向左和向上移动固定大小 div 宽度和高度的一半。
.className{
width:270px;
height:150px;
position:absolute;
left:50%;
top:50%;
margin:-75px 0 0 -135px;
}
jQuery
$(document).ready(function(){
$(window).resize(function(){
$('.className').css({
position:'absolute',
left: ($(window).width() - $('.className').outerWidth())/2,
top: ($(window).height() - $('.className').outerHeight())/2
});
});
// To initially run the function:
$(window).resize();
});
【讨论】:
这并不像人们想象的那么容易——如果您知道容器的高度,您实际上只能进行垂直对齐。如果是这种情况,您可以使用绝对定位。
概念是将顶部/左侧位置设置为 50%,然后使用负边距(设置为高度/宽度的一半)将容器拉回居中。
示例:http://jsbin.com/ipawe/edit
基本 CSS:
#mydiv {
position: absolute;
top: 50%;
left: 50%;
height: 400px;
width: 700px;
margin-top: -200px; /* -(1/2 height) */
margin-left: -350px; /* -(1/2 width) */
}
【讨论】:
这个网站提供了一些垂直居中 div 的选项:http://www.jakpsatweb.cz/css/css-vertical-center-solution.html
【讨论】:
【讨论】: