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

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


当前回答

这是最好的代码,以中心的div机器人水平和垂直

div { 位置:绝对的; 上图:50%; 左:50%; 变换:翻译(-50%,-50%); }

其他回答

I'm surprised this has not been mentioned yet, but the simplest way to do this would be by setting the height, margin (and width, if you want) using viewport sizes. As you might know, total height of the viewport = 100vh. Say you want the height of you container to occupy 60% (60vh) of the screen, you can divide the rest (40vh) equally between the top and the bottom margin so that the element aligns itself in the centre automatically. Setting the margin-left and margin-right to auto, will make sure the container is centred horizontally.

.container { 宽度:60大众;/ *可选* / 高度:60 vh; 利润率:20vh auto; 背景:# 333; } < div class = "容器" > < / div >

最好和最灵活的方式

这个演示的主要技巧是,在元素从上到下的正常流中,因此margin-top: auto被设置为零。然而,绝对定位元素对于自由空间的分布具有相同的作用,并且类似地可以在指定的顶部和底部垂直居中(在IE7中不起作用)。

这个技巧适用于任何大小的div。

div { 宽度:100 px; 身高:100 px; 背景颜色:红色; 位置:绝对的; 上图:0; 底部:0; 左:0; 右:0; 保证金:汽车; } < div > < / div >

这里还有一个方法(防弹),利用“display:table”规则:

标记

<div class="container">
  <div class="outer">
    <div class="inner">
      <div class="centered">
        ...
      </div>
    </div>
  </div>
</div>

CSS:

.outer {
  display: table;
  width: 100%;
  height: 100%;
}
.inner {
  display: table-cell;
  vertical-align: middle;
  text-align: center;
}
.centered {
  position: relative;
  display: inline-block;

  width: 50%;
  padding: 1em;
  background: orange;
  color: white;
}

解决方案

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

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

我认为有两种方法使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