zoukankan      html  css  js  c++  java
  • div的水平居中和垂直居中

    div是html中的一个标签,一般称之为盒子。有宽度、有高度,是可以存放内容的一个区域。但是如何让div在页面上以水平或者垂直的方式居中呢?

    1.div水平居中

      div水平居中其实很简单,只要使用到margin中的auto就能实现。代码如下:

    <html>
        <head>
            <title>div水平居中</title>
            
            <style>
                .horizontal{
                    width:800px;
                    height:300px;
                    background: #ff6a00;
                    margin:100px auto;        /*100px是div的上下边距,auto表示左右边距自适应(即水平居中)*/
                }
            </style>
        </head>
        <body>
            <div class="horizontal">
                我是水平居中的div
            </div>
        </body>
    </html>

    2.div垂直居中

      div垂直居中的方法一般是使用absolute定位(绝对定位)的方式来实现的。代码如下:

    <html>
        <head>
            <title>div水平垂直居中</title>
            
            <style>
                .divbox{
                    width:500px;
                    height:300px;
                    line-height:300px;
                    text-align:center;
                    background:#ccc;
                    
                    position:absolute;
                    left:50%;
                    top:50%;
                    margin-left:-250px;
                    margin-top:-150px;
                }
            </style>
        </head>
        <body>
            <div class="divbox">
                我是水平垂直居中的div
            </div>
        </body>
    </html>

      position:absolute表示divbox定位方式为绝对定位。绝对定位是一种让定位元素脱离文档流的定位方式,通过设置left、right、top、bottom属性值就可以定位div了。left:50%;top:50%;表示div在整个窗口中居中。但是这里有一点需要注意的是,此时是div的左上角在窗口中居中,整个div其实并不是居中的。所以在这里设置了margin-left属性和margin-top属性,它们的值分别为宽度和高度的1/2,单位为负值。这里div本身就有宽度和高度,设置margin-left和margin-top就是将div以左上角为原点向左平移(width/2)px 、向上平移(height/2)px 此时div就是水平和垂直居中的。

  • 相关阅读:
    Tensorflow入门:Linear Regression
    日语动词变形总结
    序列模型第二周作业2:Emojify!
    序列模型第二周作业1:Operations on word vectors
    序列模型第一周作业3: Improvise a Jazz Solo with an LSTM Network
    序列模型第一周作业2: Character level language model
    序列模型第一周作业1: Building your Recurrent Neural Network
    Bidirectional RNN (BRNN)
    Long Short term memory unit(LSTM)
    propertyGrid使用
  • 原文地址:https://www.cnblogs.com/reese/p/4968044.html
Copyright © 2011-2022 走看看