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

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


当前回答

2018年使用CSS网格的方式:

.parent{
    display: grid;
    place-items: center center;
}

检查浏览器的支持,Caniuse建议它适用于Chrome 57、FF 52、Opera 44、Safari 10.1和Edge 16。我没有检查自己。

请看下面的片段:

.parent { 显示:网格; 放置物品:中心中心; /*place-items是align-items和justification -items的简写*/ 身高:200 px; 边框:1px纯黑色; 背景:gainsboro; } .child { 背景:白色; } < div class = "父" > < div class = "孩子" >为中心!< / div > < / div >

其他回答

抱歉回复晚了 最好的办法是

  div {
      position: fixed;
      top: 50%;
      left: 50%;
      margin-top: -50px;
      margin-left: -100px;
    }

上边距和左边距应该根据你的div框大小

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

演示:

看看这个演示。

position: absolute;
left: 50%;
top: 50%;
-webkit-transform: translate(-50%, -50%);
-ms-transform: translate(-50%, -50%);
transform: translate(-50%, -50%);

解释:

给它一个绝对定位(父元素应该有相对定位)。然后,左上角被移动到中心。因为你还不知道宽度/高度,所以你使用css transform来转换相对于中间的位置。平移(-50%,-50%)会将左上角的x和y位置降低50%的宽度和高度。

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

外容器

应有显示:表;

内容器

应该有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进行定位。

这里还有一个方法(防弹),利用“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;
}