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

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


当前回答

是浏览器支持的,使用翻译功能强大。

position: absolute;
background-color: red;

width: 70%;     
height: 30%; 

/* The translate % is relative to the size of the div and not the container*/ 
/* 21.42% = ( (100%-70%/2) / 0.7 ) */
/* 116.666% = ( (100%-30%/2) / 0.3 ) */
transform: translate3d( 21.42%, 116.666%, 0);

其他回答

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

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

我在看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 {
    border-style: solid;
    position: fixed;
    width: 80%;
    height: 80%;
    left: 10%;
    top: 10%;
}

调整左侧和顶部的宽度和高度,即(100% - 80%)/ 2 = 10%

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

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

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