CSS如何让div相对body居中 而其中的控件不受影响。

html-css016

CSS如何让div相对body居中 而其中的控件不受影响。,第1张

需要准备的材料分别有:电脑、浏览器、html编辑器。

1、首先,打开html编辑器,新建html文件,例如:index.html。

2、将index.html中的<body>替换为:

<body style="text-align: center">

<div style="margin:autowidth: 200pxheight: 70pxborder: 1px solid bluetext-align: left">

<span>123</span>

</div>

</body>

3、浏览器运行index.html页面,此时div相对body是居中,而div中的内容并没有受影响。

<!DOCTYPE html>

<html lang="en">

<head>

    <meta charset="UTF-8">

    <title>Document</title>

    <style type="text/css">

    /*这种需要最新的浏览器才支持*/

     body {

        display: -webkit-flex

        display: -moz-flex

        display: -ms-flex

        display: -o-flex

        display: flex

        height: 100vh/*高度为浏览器高度最大值*/

    }

    /*这种方法的不用确定div的宽高*/

    

    body .box {

        margin: auto

        background: #efefef

    }

   

    /*这种是最常用的,但是要确定某个div的宽高值*/

    

    body {

        position: relative

        height: 100vh

    }

    

    body .box {

        position: absolute

        background: #efefef

        width: 100px

        height: 100px

        left: 50%

        top: 50%

        margin-left: -50px/*宽度值的负一半*/

        margin-top: -50px/*高度值的负一半*/

    }

    </style>

</head>

<body>

    <div class="box">

        这里是内容

    </div>

</body>

</html>

为body的内容加边框,就在body里面设置个div ,然后设置它的属性,比如:边框boder:1px solid #f00居中:margin:auto;层里面的内容你不设置还是原来的样子。