CSS居中问题大总结

本文详细总结了CSS实现元素水平垂直居中的多种方法,包括使用Flexbox、Grid布局、传统方法等,深入探讨每种方法的适用场景及优缺点,帮助开发者更好地理解和应用CSS居中技巧。
摘要由CSDN通过智能技术生成
<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <meta http-equiv="X-UA-Compatible" content="ie=edge" />
    <title>Document</title>
    <style>
      /* 
      一,水平居中
      方法1 :行内元素   (父元素)text-align,(子元素)inline-block
      .parent{text-align: center;}                 
      .child{display: inline-block;} 
      总结:
      优点:兼容性好,支持低版本浏览器
      缺点:需要同时在父元素和子元素上设置
      适用场景:子元素数量少(或只有一个),并且需要兼容低版本浏览器时使用,不受float影响
       */
      .parent1 {
        background: red;
        height: 200px;
        text-align: center;
      }
      .child1 {
        background: blue;
        display: inline-block;
        width: 100px;
        height: 100px;
      }
      /* 
      一,水平居中
      方法2:块状元素   使用margin:0 auto来实现
      .child{width:200px;margin:0 auto;} 
      优点:兼容性好
      缺点:需要指定宽度
      前提:用于子元素上,不受float影响
       */
      .parent2 {
        background: red;
        height: 200px;
      }
      .child2 {
        background: blue;
        width: 100px;
        height: 100px;
        margin: 0 auto;
      }
      /* 
      一,水平居中
      方法3:(子元素)display:table;margin:0 auto;
      .child{display:table;margin:0 auto;} 
      优点:只需要对自身进行设置 ,子元素宽高不固定的情况可以使用
      缺点:不兼容IE6和IE7
      适用场景:子元素数量多,子元素宽高不固定的情况可以使用,不方便修改父元素的属性,对浏览器版本要求相对较低时使用
       */
      .parent3 {
        background: red;
        height: 200px;
      }
      .child3 {
        color: white;
        
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值