Home > Web Front-end > CSS Tutorial > Why Does a CSS Input with `width: 100%` Extend Beyond Its Parent's Bounds?

Why Does a CSS Input with `width: 100%` Extend Beyond Its Parent's Bounds?

Barbara Streisand
Release: 2024-11-28 11:03:12
Original
327 people have browsed it

Why Does a CSS Input with `width: 100%` Extend Beyond Its Parent's Bounds?

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

Why does this happen?

In CSS, the width and height properties set the size of the content box. However, padding is added outside the content box, increasing the element's overall size.

When you set an element with padding to width: 100%, its padding makes it wider than 100% of its containing element.

The Solution

To prevent padding from affecting an element's width or height, use the box-sizing property set to border-box:

box-sizing: border-box;
Copy after login

This makes the width and height properties include the padding and border, resulting in a total width of 100%.

Browser Compatibility

box-sizing has good browser compatibility (IE8 ). No prefixes are required.

Alternative Approach: "Inherited" Box Sizing

Some experts recommend using the following "inherited" approach:

html {
  box-sizing: border-box;
}
*, *:before, *:after {
  box-sizing: inherit;
}
Copy after login

This sets box-sizing to border-box for the entire document, and allows all elements to inherit that setting.

Demonstration

Here's a demonstration with the border-box applied to the input elements:

input[type=text],
input[type=password] {
  width: 100%;
  box-sizing: border-box;
}
Copy after login

The above is the detailed content of Why Does a CSS Input with `width: 100%` Extend Beyond Its Parent's Bounds?. 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