CSS:width:100% 和 width:auto的区别

329 阅读1分钟

情况一

无边框、无内边距、无外边距

    <div class="box">
        <div class="box1">box1</div>
        <div class="box2">box2</div>
    </div>
        .box{
            width: 600px;
        }
        .box1{
            width: 100%;
            height: 50px;
            background-color: blue;
        }
        .box2{
            width: auto;
            height: 50px;
            background-color: blue;
        }

image.png

情况二

有边框、无内边距、无外边距

        .box1{
            width: 100%;
            height: 50px;
            background-color: blue;
            border: 5px solid red;
        }

image.png

        .box2{
            width: auto;
            height: 50px;
            background-color: blue;
            border: 5px solid red;
        }

image.png

情况三

有边框、有内边距、无外边距

        .box1{
            width: 100%;
            height: 50px;
            background-color: blue;
            border: 5px solid red;
            padding:10px;
        }

image.png

        .box2{
            width: auto;
            height: 50px;
            background-color: blue;
            border: 5px solid red;
            padding:10px;
        }

image.png

情况四

有边框、有内边距、有外边距

        .box1{
            width: 100%;
            height: 50px;
            background-color: blue;
            border: 5px solid red;
            padding:10px;
            margin: 10px;
        }

image.png

        .box2{
            width: auto;
            height: 50px;
            background-color: blue;
            border: 5px solid red;
            padding:10px;
            margin: 10px;
        }

image.png

总结

width:100%和width:auto区别:

  • width:100%:添加padding或border或margin会超出父类原本的宽度
  • width:auto:添加padding或border或margin不会超出父类原本的宽度