zoukankan      html  css  js  c++  java
  • 块级元素居中问题

    第一次尝试写点东西,不喜勿喷。

    一、块级元素水平居中,直接左右margin值设为自动就ok。

    div{

      margin: 0 auto;

    }

    二、让块级元素水平垂直居中于父级元素

    1、已知宽高的情况下,万能的position定位法,子元素设置top:50% left:50%,margin-left  margin—top值设置为改块元素宽高的一半,

    这样可以达到水平和垂直居中。注:父级元素position必须设置为relative,不然达不到效果(我们一般认为只需要给子元素设置position:absolute就ok了,这里能实现相对于父级定位,定位为出现偏移,这个由于定位值采取的是%制造成的,原因不明)。

    <---html--->

    <div class="test">
    <div class="test1">
    </div>
    </div>

    <---css--->

    .test{
    position: relative;
    height: 500px;
    500px;
    background: deepskyblue;
    }
    .test1{
    position: absolute;
    top: 50%;
    left: 50%;
    height: 100px;
    100px;
    background: darkmagenta;
    margin-top: -50px;
    margin-left: -50px;
    }

    2、未知块宽高的情况下,这里可以模拟table标签属性,达到让块级元素水平垂直居中。(需要在居中的块级元素外套一层,这样可以实现水平垂直集中,无论居中块元素的宽高为多少,都可以实现居中)

    <---html--->

    <div class="test">
    <div class="test1">
    <div class="test2">
    </div>
    </div>
    </div>

    <---css--->

    .test{
    height: 500px;
    500px;
    background: deepskyblue;
    display: table;
    }
    .test1{
    display: table-cell;
    vertical-align: middle;
    }
    .test2{
    margin: 0 auto;
    height: 300px;
    300px;
    background: darkmagenta;
    }

    3、已知块宽高的情况下,也可以用position定位法实现,top left right bottom 设置为0。

    <---html--->

    <div class="test">
    <div class="test1">

    </div>
    </div>

    <---css--->

    .test{
    position: relative;
    height: 500px;
    500px;
    background: deepskyblue;
    }
    .test1{
    position: absolute;
    margin: auto;
    height: 300px;
    300px;
    top: 0;
    left: 0;
    right: 0;
    bottom: 0;
    background: darkmagenta;
    }
    最新  自需要在父级盒子上加
     /*只需要在父元素上加这三句*/
    justify-content: center; /*子元素水平居中*/
    align-items: center; /*子元素垂直居中*/
    display: -webkit-flex;
    
    
  • 相关阅读:
    安装django时出错
    mysql ------python3(一)笔记
    安装mysql的具体过程
    Python3web框架---Django、Tornado、Flask的对比
    python3-----json函数
    图片人脸识别年龄和性别
    urllib库的使用(三)-----python3 异常处理
    python 3 基础篇 (一)
    requests,pymysql,django的安装
    求素数方法的改进
  • 原文地址:https://www.cnblogs.com/DivHao/p/6382456.html
Copyright © 2011-2022 走看看