<div>元素在页面中垂直和水平的最佳方法?
我知道左边距:auto;margin-right:汽车;会以水平方向为中心,但是垂直方向的最佳方法是什么呢?
<div>元素在页面中垂直和水平的最佳方法?
我知道左边距:auto;margin-right:汽车;会以水平方向为中心,但是垂直方向的最佳方法是什么呢?
当前回答
请使用以下CSS属性水平和垂直居中对齐元素。这对我来说很有效。
div {
position: absolute;
left: 0;
top: 0;
right: 0;
bottom: 0px;
margin: auto;
width: 100px;
height: 100px;
}
其他回答
div { 位置:绝对的; 上图:50%; 左:50%; 转换:翻译(-50%,-50%); -ms-transform: -50%, -50%;/*即9 */ -webkit-transform (-50%, -50%);/* Chrome, Safari, Opera */ } <身体> <div> div要垂直对齐 < /身体>
位置:主体文档中的绝对div
有位置的元素:绝对的;相对于最近的定位祖先(而不是相对于视口(主体标记),像固定的那样)定位。
然而;如果绝对定位元素没有定位父元素,它将使用文档主体,并随着页面滚动而移动。
来源:CSS位置
下面是我之前写的一个脚本(它是用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();
};
尽管当OP问这个问题时,这并没有起作用,但我认为,至少对于现代浏览器来说,最好的解决方案是使用display: flex或伪类。
你可以在下面的小提琴中看到一个例子。 这是更新后的小提琴。
对于伪类,一个例子可以是:
.centerPseudo {
display:inline-block;
text-align:center;
}
.centerPseudo::before{
content:'';
display:inline-block;
height:100%;
vertical-align:middle;
width:0px;
}
display: flex的用法,根据css-tricks和MDN说明如下:
.centerFlex {
align-items: center;
display: flex;
justify-content: center;
}
flex还有其他可用的属性,在上面提到的链接中解释了这些属性,并提供了进一步的示例。
如果你必须支持不支持css3的旧浏览器,那么你可能应该使用javascript或其他答案中显示的固定宽度/高度解决方案。
实际上有一个解决方案,使用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小提琴演示
解决方案
仅使用两行CSS,利用Flexbox的神奇力量
.parent { display: flex; }
.child { margin: auto }