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

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


当前回答

如果你正在使用JQuery,你可以使用.position();

<div class="positionthis"></div>

CSS

.positionthis {
    width:100px;
    height:100px;
    position: absolute;
    background:blue;
}

Javascript JQuery ()

$(document).ready(function () {
    $('.positionthis').position({
        of: $(document),
        my: 'center center',
        at: 'center center',
        collision: 'flip flip'
    });
});

http://jsfiddle.net/vx9gV/

其他回答

如果你正在使用JQuery,你可以使用.position();

<div class="positionthis"></div>

CSS

.positionthis {
    width:100px;
    height:100px;
    position: absolute;
    background:blue;
}

Javascript JQuery ()

$(document).ready(function () {
    $('.positionthis').position({
        of: $(document),
        my: 'center center',
        at: 'center center',
        collision: 'flip flip'
    });
});

http://jsfiddle.net/vx9gV/

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 >

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

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

演示:

看看这个演示。

如果你知道div的定义大小,你可以使用calc。

实例:https://jsfiddle.net/o8416eq3/

注意:只有当你在CSS中硬编码了' ' div '的宽度和高度时,这才有效。

目标# { 位置:固定; 顶部:calc(50vh - 100px/2); 左:calc(50vw - 200px/2); 宽度:200 px; 身高:100 px; 背景颜色:红色; } < div id = '目标' > < / div >