什么是盒子模型,怎样使用

1、首先盒子模型有两种,W3C的标盒模型和IE的怪异盒子模型

2、两者的区别

1)、盒子模型包括margin、padding、content、border,而W3C标准盒子模型的元素宽度width=content的宽度

而IE怪异盒子模型的元素宽度width=content+padding+border

2)、IE的怪异盒子模型元素宽度的定义更能让人理解,W3C也认识到了这一点,所以在css3中添加了一个样式box-sizing,它有两个属性,分别是content-box和border-box

  • content-box:指元素的width=content+padding+border
  • border-box:指元素的width=content

 

3、盒子模型中使用margin:0 auto;需注意的地方

1)、使用margin: 0 auto;水平居中盒子必须有width,要有明确width

2)、只有标准流下的盒子才能使用margin:0 auto; 

当一个盒子浮动了,固定定位,绝对定位,margin:0 auto; 不能用了

3)、margin:0 auto;是居中盒子,而不是居中文本,文字水平居中使用text-align: center;

注意:margin:0 auto;失效的原因

  1. 要给居中的元素一个宽度,否则无效。
  2. 该元素一定不能浮动或绝对定位,否则无效。
  3. 在HTML中使用<center></center>标签,需考虑好整体构架,否者全部元素都会居中的。
  4. 有时需要给父级元素添加text-align: center;
  5. 有时可能涉及到 <!DOCTYPE>类型相关定义。
     

   4、顺便说一下web开发中让盒子居中的办法 

  • margin固定宽高居中;
  • 负margin居中;
  • #container {
        position: relative;
        width: 600px;
        height: 500px;
        border: 1px solid #000;
        margin: auto;
    }
    #box {
        position: absolute;
        width: 200px;
        height: 200px;
        left: 50%;
        top: 50%;
        margin: -100px -100px;注意-100=width/2

        background-color: #0ff;
  • 绝对定位居中;
  • #container {
        position: relative;
        width: 600px;
        height: 500px;
        border: 1px solid #000;
        margin: auto;
    }
    #box {
        position: absolute;
        width: 200px;
        height: 200px;
        left: 0;
        top: 0;
        right: 0;
        bottom: 0;
        margin: auto;

        background-color: #0ff;
  • flex居中;
  • transform居中;
  • #container {
        position: relative;
        width: 600px;
        height: 600px;
        border: 1px solid #000;
        margin: auto;
    }
    #box {
        position: relative;
        top: 50%;
        left: 50%;
        width: 200px;
        height: 200px;
        transform: translate(-50%, -50%);
        -webkit-transform: translate(-50%, -50%);
        -ms-transform: translate(-50%, -50%);
        -moz-transform: translate(-50%, -50%);
        background-color: #0ff;
    }
  • 不确定宽高居中(绝对定位百分数);
  • 这种不确定宽高的居中,较为灵活。只需要保证left和right的百分数一样就可以实现水平居中,保证top和bottom的百分数一样就可以实现垂直居中。
    CSS:

    #container {
        position: relative;
        width: 600px;
        height: 500px;
        border: 1px solid #000;
        margin: auto;
    }
    #box {
        position: absolute;
        left: 30%;
        right: 30%;
        top: 25%;
        bottom: 25%;

        background-color: #0ff;

 

  • 3
    点赞
  • 10
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值