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

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


当前回答

我在看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>

结果如下所示:

其他回答

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

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

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

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

请看下面的片段:

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

演示:

看看这个演示。

使用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获取更多信息。

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

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