zoukankan      html  css  js  c++  java
  • css绝对居中的几种方法

    利用CSS进行元素的水平居中,比较简单。

    行级元素设置其父元素的text-align center,块级元素设置其本身的left 和 right margins为auto即可。

    本文收集了几种利用css进行元素的垂直居中的方法,每一种适用于不同的情况,可以对号入座,选择适合自己的方法

    第一种:知道宽度的行级元素( 父元素设置text-align: center,本身设置行高)
     
    html:
    <div id="parent1">
      <div id="child1">Content here</div>
    </div>
     
    css:
    #parent1{ 400px; background: #ccc;text-align: center;}
    #child1 {line-height: 200px;}
     
     
     
    第二种:设置内边距padding
     
    html:
    <div id="parent2">
      <div id="child2">Content here</div>
    </div>
     
    css:
    #parent2{ 400px; background: #ccc;text-align: center;}
    #child2{padding:30px 0;}
     
     
     
    第三种:flex布局(⚠️注意兼容性问题)
    只需要给父元素加上flex
     
    html:
    <div id="parent3">
      <div id="child3">Content here</div>
    </div>
     
    css:
    #parent3{ 400px;height: 100px; background: #ccc;display: flex;align-items: center;justify-content: center;}
     

    第四种:position : absolute + transform:translate()

    html:

    <div id="parent4">
      <div id="child4">Content here</div>
    </div>
     
     
    css:
    #parent4{ 400px;height: 100px; background: #ccc;position: relative;}
    #child4{position: absolute;top: 50%;left: 50%;transform: translate(-50%,-50%);}
     
     
     
    第五种:display : table-cell
     
    html:
    <div id="parent5">
      <div id="child5">Content here</div>
    </div>
     
     
    css:
    #parent5{ 400px;height: 200px; background: #ccc;display: table;}
    #child5{display: table-cell;vertical-align: middle;text-align: center;}
     
     
  • 相关阅读:
    call()与apply()的作用与区别
    Tomcat8/9的catalina.out中文乱码问题解决
    怎样查看Jenkins的版本
    每日日报2020.8.18
    528. Random Pick with Weight
    875. Koko Eating Bananas
    721. Accounts Merge
    515. Find Largest Value in Each Tree Row
    286. Walls and Gates (Solution 1)
    408. Valid Word Abbreviation
  • 原文地址:https://www.cnblogs.com/cy1314/p/15149109.html
Copyright © 2011-2022 走看看