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

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


当前回答

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

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

其他回答

在父元素上使用display:grid并将margin:auto设置为居中元素即可:

请看下面的片段:

html,身体{ 宽度:100%; 高度:100%; 保证金:0; 填充:0; } .container { 显示:网格; 高度:90%; 背景颜色:蓝色; } .content { 保证金:汽车; 颜色:白色; } < div class = "容器" > <div class="content"> cented div here</div> < / div >

我在看Laravel的视图文件,注意到他们完美地将文本居中。我立刻想起了这个问题。 他们是这样做的:

<html>
<head>
    <title>Laravel</title>

    <!--<link href='//fonts.googleapis.com/css?family=Lato:100' rel='stylesheet' type='text/css'>-->

    <style>
        .container {
            margin: 0;
            padding: 0;
            width: 100%;
            height: 100%;
            display: table;

        }

        .inside {
            text-align: center;
            display: table-cell;
            vertical-align: middle;
        }


    </style>
</head>
<body>
    <div class="container">
            <div class="inside">This text is centered</div>
    </div>
</body>

结果如下所示:

请使用以下CSS属性水平和垂直居中对齐元素。这对我来说很有效。

div {
  position: absolute;
  left: 0;
  top: 0;
  right: 0;
  bottom: 0px;
  margin: auto;
  width: 100px;
  height: 100px;
}

虽然我太晚了,但这很简单。页面中心总是向左50%,顶部50%。减去div width和height的50%设置左右边距。希望它适用于所有地方

身体{ 背景:# EEE; } .center-div { 位置:绝对的; 宽度:200 px; 高度:60 px; 左:50%; margin-left: -100 px; 上图:50%; margin-top: -30 px; 背景:# CCC; 颜色:# 000; text-align:中心; } < div class = " center-div”> <h3>这是中心div</h3> < / div >

利用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)。