<div>元素在页面中垂直和水平的最佳方法?
我知道左边距:auto;margin-right:汽车;会以水平方向为中心,但是垂直方向的最佳方法是什么呢?
<div>元素在页面中垂直和水平的最佳方法?
我知道左边距:auto;margin-right:汽车;会以水平方向为中心,但是垂直方向的最佳方法是什么呢?
当前回答
利用Flex显示的简单解决方案
<div style = 'display:flex; position:absolute; top:0; bottom:0; right:0; left:0; '>
<div id = 'div_you_want_centered' style = 'margin:auto;'>
This will be Centered
</div>
</div>
查看http://css-tricks.com/snippets/css/a-guide-to-flexbox/
第一个div占据了整个屏幕,并有一个针对每种浏览器的显示:flex集。第二个div(居中div)充分利用了显示:flex div,其中margin:auto工作出色。
注意兼容IE11+。(IE10 w/ prefix)。
其他回答
下面是我之前写的一个脚本(它是用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();
};
实际上有一个解决方案,使用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小提琴演示
在父元素上使用display:grid并将margin:auto设置为居中元素即可:
请看下面的片段:
html,身体{ 宽度:100%; 高度:100%; 保证金:0; 填充:0; } .container { 显示:网格; 高度:90%; 背景颜色:蓝色; } .content { 保证金:汽车; 颜色:白色; } < div class = "容器" > <div class="content"> cented div here</div> < / div >
尽管当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或其他答案中显示的固定宽度/高度解决方案。
使用Flex-box在我看来:
#{母公司 显示:flex; justify-content:中心; 对齐项目:中心; } < div id = "父" > <div id="child">Hello World!< / div > < / div >
您可以看到,只有三个CSS属性可以用于将子元素垂直和水平居中。显示:flex;通过激活Flex-box display来完成主要部分,justify-content: center;将子元素垂直居中并对齐-items: Center;水平居中。为了看到最好的结果,我只添加了一些额外的样式:
#{母公司 显示:flex; justify-content:中心; 对齐项目:中心; 身高:500 px; 宽度:500 px; 背景:黄色; } #孩子{ 宽度:100 px; 身高:100 px; 背景:银色; } < div id = "父" > <div id="child">Hello World!< / div > < / div >
如果你想了解更多关于Flex-box的知识,你可以访问W3Schools, MDN或CSS-Tricks获取更多信息。