Skip to main content

What is the difference between width property 100% and auto in css?

 width:auto: The default width value of block-level elements. When set to this value, the browser will automatically select an appropriate width value to adapt to the width of the parent element. When the width is set to 100%, the width of the child element box The value is equal to the parent's content, and as the parent's content automatically changes, after adding the padding and margin of the child element, its width remains unchanged, which is the difference from setting it to auto. But we most often use width:auto, because it is more flexible, width:100% is used less, because when adding padding or margin, this method is easy to make it exceed the parent box and destroy the original layout.

The following is the actual code demonstration, the picture intuitively reflects the difference between the two.

<style>
        .outer{
            background-color: aquamarine;
            width: 200px;
            height: 200px;
        }
        .inner1{
            height: 50px;
            width: auto;
            background-color: pink;
            padding: 10px;
            border: 5px solid red;
            margin: 5px;
        }
        .inner2{
            height: 50px;
            width: 100%;
            padding: 10px;
            background-color: yellow;
            border: 5px solid red;
            margin: 5px;
        }
    </style>
</head>
<body>
    <div class="outer">
        <div class="inner1">

        </div>
        <hr>
        <div class="inner2">
           
        </div>
    </div>



Comments

Popular posts from this blog

What is the difference between the box-size property content-box and border-box in the css box model?

 The box model is a very important concept in CSS layout, it includes content area, padding, border, and margin. Box models can be divided into two types: standard box models and IE box models. The box model, as the name suggests, is used to hold things, and the things it holds are the content of HTML elements. In other words, every visible HTML element is a box.

Js uses recursive way to traverse the dom tree to dynamically create element nodes

 What is a dom tree? In short, DOM is the Document Object Model, which provides a structured representation for documents and defines how to access the document structure through scripts. DOM is composed of nodes. After the HTML is loaded, the rendering engine will generate a DOM tree in memory based on the HTML document. This article uses a small case to traverse the dom tree recursively. The core of the method is to determine whether the incoming data is an array, and then traverse the root node. Note that there must be an end condition when using recursion.