<div>元素在页面中垂直和水平的最佳方法?

我知道左边距:auto;margin-right:汽车;会以水平方向为中心,但是垂直方向的最佳方法是什么呢?


当前回答

解决方案

仅使用两行CSS,利用Flexbox的神奇力量

.parent { display: flex; }
.child { margin: auto }

其他回答

div {
    border-style: solid;
    position: fixed;
    width: 80%;
    height: 80%;
    left: 10%;
    top: 10%;
}

调整左侧和顶部的宽度和高度,即(100% - 80%)/ 2 = 10%

另一个答案是这样的。

<div id="container"> 
    <div id="centered"> </div>
</div>

还有css:

#container {
    height: 400px;
    width: 400px;
    background-color: lightblue;
    text-align: center;
}

#container:before {
    height: 100%;
    content: '';
    display: inline-block;
    vertical-align: middle;
}

#centered {
    width: 100px;
    height: 100px;
    background-color: blue;
    display: inline-block;
    vertical-align: middle;
    margin: 0 auto;
}

我喜欢的方法是将一个盒子垂直和水平居中,是以下技术:

外容器

应有显示:表;

内容器

应该有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 { 位置:绝对的; 上图:50%; 左:50%; 转换:翻译(-50%,-50%); -ms-transform: -50%, -50%;/*即9 */ -webkit-transform (-50%, -50%);/* Chrome, Safari, Opera */ } <身体> <div> div要垂直对齐 < /身体>

位置:主体文档中的绝对div

有位置的元素:绝对的;相对于最近的定位祖先(而不是相对于视口(主体标记),像固定的那样)定位。

然而;如果绝对定位元素没有定位父元素,它将使用文档主体,并随着页面滚动而移动。

来源:CSS位置

我知道我迟到了,但是这里有一种方法可以将一个维度未知的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>

演示:

看看这个演示。