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

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


当前回答

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

请看下面的片段:

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

其他回答

这个解决方案对我很有效

    .middleDiv{
        position : absolute;
        height : 90%;
        bottom: 5%;
    }

(或高度:70% /底部:15%

高度:40% /底部:30%…)

虽然我太晚了,但这很简单。页面中心总是向左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 >

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

  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>

演示:

看看这个演示。

下面是我之前写的一个脚本(它是用jQuery库写的):

var centerIt = function (el /* (jQuery element) Element to center */) {
    if (!el) {
        return;
    }
    var moveIt = function () {
        var winWidth = $(window).width();
        var winHeight = $(window).height();
        el.css("position","absolute").css("left", ((winWidth / 2) - (el.width() / 2)) + "px").css("top", ((winHeight / 2) - (el.height() / 2)) + "px");
    }; 
    $(window).resize(moveIt);
    moveIt();
};