Why does a CSS input with `width: 100%` extend beyond its parent's boundaries?

Patricia Arquette
Release: 2024-11-11 12:35:03
Original
650 people have browsed it

Why does a CSS input with `width: 100%` extend beyond its parent's boundaries?

CSS Input with width: 100% goes outside parent's bound

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!

The Cause – Padding's Deviant Nature

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.

Box-sizing to the Rescue

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.

Advanced Inheritance Technique

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;
}
Copy after login

Demonstration

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;
}
Copy after login

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!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template