<div>元素在页面中垂直和水平的最佳方法?
我知道左边距:auto;margin-right:汽车;会以水平方向为中心,但是垂直方向的最佳方法是什么呢?
<div>元素在页面中垂直和水平的最佳方法?
我知道左边距:auto;margin-right:汽车;会以水平方向为中心,但是垂直方向的最佳方法是什么呢?
当前回答
如果你正在使用JQuery,你可以使用.position();
<div class="positionthis"></div>
CSS
.positionthis {
width:100px;
height:100px;
position: absolute;
background:blue;
}
Javascript JQuery ()
$(document).ready(function () {
$('.positionthis').position({
of: $(document),
my: 'center center',
at: 'center center',
collision: 'flip flip'
});
});
http://jsfiddle.net/vx9gV/
其他回答
我认为有两种方法使div中心对齐通过CSS。
.middleDiv {
position : absolute;
width : 200px;
height : 200px;
left : 50%;
top : 50%;
margin-left : -100px; /* half of the width */
margin-top : -100px; /* half of the height */
}
这是最简单最好的方法。演示请访问以下链接:
http://w3webpro.blogspot.in/2013/07/how-to-make-div-horizontally-and.html
使用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获取更多信息。
利用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)。
我喜欢的方法是将一个盒子垂直和水平居中,是以下技术:
外容器
应有显示:表;
内容器
应该有display: table-cell; 应该有垂直对齐:中间; 应该有text-align: center;
内容框
应该有显示:inline-block; 应该重新调整水平文本对齐,如。text-align:左;或者text-align: right;,除非你想让文本居中
这种技术的优雅之处在于,你可以将你的内容添加到内容框中,而不用担心它的高度或宽度!
Demo
body { margin : 0; } .outer-container { position : absolute; display: table; width: 100%; /* This could be ANY width */ height: 100%; /* This could be ANY height */ background: #ccc; } .inner-container { display: table-cell; vertical-align: middle; text-align: center; } .centered-content { display: inline-block; text-align: left; background: #fff; padding : 20px; border : 1px solid #000; } <div class="outer-container"> <div class="inner-container"> <div class="centered-content"> You can put anything here! </div> </div> </div>
看看这小提琴!
EDIT
是的,我知道你可以通过transform实现或多或少相同的灵活性:translate(-50%, -50%);或者transform: translate3d(-50%,-50%, 0);,我建议的技术有更好的浏览器支持。即使使用浏览器前缀,如-webkit, -ms或-moz, transform也不能提供完全相同的浏览器支持。
所以如果你关心旧的浏览器(例如。IE9及以下版本),您不应该使用transform进行定位。
div {
border-style: solid;
position: fixed;
width: 80%;
height: 80%;
left: 10%;
top: 10%;
}
调整左侧和顶部的宽度和高度,即(100% - 80%)/ 2 = 10%