<div>元素在页面中垂直和水平的最佳方法?
我知道左边距:auto;margin-right:汽车;会以水平方向为中心,但是垂直方向的最佳方法是什么呢?
<div>元素在页面中垂直和水平的最佳方法?
我知道左边距:auto;margin-right:汽车;会以水平方向为中心,但是垂直方向的最佳方法是什么呢?
当前回答
div { 位置:绝对的; 上图:50%; 左:50%; 转换:翻译(-50%,-50%); -ms-transform: -50%, -50%;/*即9 */ -webkit-transform (-50%, -50%);/* Chrome, Safari, Opera */ } <身体> <div> div要垂直对齐 < /身体>
位置:主体文档中的绝对div
有位置的元素:绝对的;相对于最近的定位祖先(而不是相对于视口(主体标记),像固定的那样)定位。
然而;如果绝对定位元素没有定位父元素,它将使用文档主体,并随着页面滚动而移动。
来源:CSS位置
其他回答
实际上有一个解决方案,使用css3,它可以垂直居中一个未知高度的div。诀窍是将div向下移动50%,然后使用transformmy将其移回中间。唯一的前提条件是要居中的元素有一个父元素。例子:
<div class="parent">
<div class="center-me">
Text, images, whatever suits you.
</div>
</div>
.parent {
/* height can be whatever you want, also auto if you want a child
div to be responsible for the sizing */
height: 200px;
}
.center-me {
position: relative;
top: 50%;
transform: translateY(-50%);
/* prefixes needed for cross-browser support */
-ms-transform: translateY(-50%);
-webkit-transform: translateY(-50%);
}
所有主流浏览器和ie9及以上版本都支持(别担心ie8,因为它在今年秋天和winxp一起死了。感谢上帝)。
JS小提琴演示
我知道我迟到了,但是这里有一种方法可以将一个维度未知的div集中在一个维度未知的父元素中。
风格:
<style>
.table {
display: table;
height: 100%;
margin: 0 auto;
}
.table-cell {
display: table-cell;
vertical-align: middle;
}
.centered {
background-color: red;
}
</style>
HTML:
<div class="table">
<div class="table-cell"><div class="centered">centered</div></div>
</div>
演示:
看看这个演示。
下面是我之前写的一个脚本(它是用jQuery库写的):
var centerIt = function (el /* (jQuery element) Element to center */) {
if (!el) {
return;
}
var moveIt = function () {
var winWidth = $(window).width();
var winHeight = $(window).height();
el.css("position","absolute").css("left", ((winWidth / 2) - (el.width() / 2)) + "px").css("top", ((winHeight / 2) - (el.height() / 2)) + "px");
};
$(window).resize(moveIt);
moveIt();
};
这个解决方案对我很有效
.middleDiv{
position : absolute;
height : 90%;
bottom: 5%;
}
(或高度:70% /底部:15%
高度:40% /底部:30%…)
抱歉回复晚了 最好的办法是
div {
position: fixed;
top: 50%;
left: 50%;
margin-top: -50px;
margin-left: -100px;
}
上边距和左边距应该根据你的div框大小