Home >Web Front-end >CSS Tutorial >Why does a CSS input with `width: 100%` extend beyond its parent's boundaries?
CSS Box Model and the Madness of Percentage Inconsistencies
In the realm of CSS, the div and its two input children seem to break free of their allotted confines. What sorcery is this?
Let's unravel this mystery!
According to the CSS box model's principles, an element's width and height play nice within the content box. Padding, however, loves to step outside this box, effectively enlarging the overall element.
Applying width: 100% to an element with padding grants it undue leeway, making it wider than its 100% parent. In this case, the inputs become widthier than their container.
To tame padding's mischievous behavior, we introduce the box-sizing property. Setting it to border-box ensures that padding remains confined within the element's defined dimensions.
Web design wizards Paul Irish and Chris Coyier advocate for the inherited approach, propagated by the following snippet:
html { box-sizing: border-box; } *, *:before, *:after { box-sizing: inherit; }
To witness the fix in action, here's the tweaked code:
input[type=text], input[type=password] { width: 100%; height: 30px; padding: 5px 10px; background-color: rgb(215, 215, 215); line-height: 20px; font-size: 12px; color: rgb(136, 136, 136); border-radius: 2px 2px 2px 2px; border: 1px solid rgb(114, 114, 114); box-shadow: 0 1px 0 rgba(24, 24, 24, 0.1); box-sizing: border-box; }
And voila! Now, no input field dares overstep its bounds. The box model's sanity is restored.
The above is the detailed content of Why does a CSS input with `width: 100%` extend beyond its parent's boundaries?. For more information, please follow other related articles on the PHP Chinese website!