我正在练习CSS,我很困惑如何在我的页面上强制我的div元素居中(vertically和horizontally) (指的是跨浏览器兼容性的一种或多种方式)?
诚挚的问候!
发布于 2011-03-24 23:15:11
有很多方法:
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> 发布于 2011-03-24 23:18:17
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();
});这是一个demo of the techniques in practice。
发布于 2011-03-24 23:19:22
这个站点提供了一些垂直居中的选项,你的div:http://www.jakpsatweb.cz/css/css-vertical-center-solution.html
https://stackoverflow.com/questions/5421334
复制相似问题