📜  width css 属性 - CSS (1)

📅  最后修改于: 2023-12-03 15:35:41.443000             🧑  作者: Mango

Width CSS 属性

The width CSS property sets the width of an element. It is specified as a length, percentage, or auto.

Syntax
/* Keyword values */
width: auto;
width: min-content;
width: max-content;
width: fit-content;

/* <length> values */
width: 100px;
width: 50%;

/* Global values */
width: inherit;
width: initial;
width: unset;
Values
Keyword values
  • auto: The element will expand to fit its content.
  • min-content: The minimum width of the element is the width of the content.
  • max-content: The maximum width of the element is the width of the content.
  • fit-content: The element will expand to fit its content, but not wider than its container.
<length> values
  • <length>: Units can be px, em, rem, etc.
Global values
  • inherit: The element inherits the width property from its parent.
  • initial: The element has the default width value.
  • unset: The element has an unspecified width value, which means it falls back to inherit if it has a parent, or to initial otherwise.
Examples
Setting width with <length> values
div {
  width: 100px; /* Sets the width of div to 100 pixels */
}

div {
  width: 50%; /* Sets the width of div to 50% of its parent element */
}
Setting width with keyword values
div {
  width: auto; /* Sets the width of div to its content height */
}

div {
  width: min-content; /* Sets the minimum width of div to its content height */
}

div {
  width: max-content; /* Sets the maximum width of div to its content height */
}

div {
  width: fit-content; /* Sets the width of the div to the width of its content, but not wider than its container */
}
Browser Compatibility

The width property is widely supported by modern browsers. However, be mindful that the keyword values are not supported by Internet Explorer and older versions of Safari.

Conclusion

The width CSS property is a fundamental tool for controlling layout on the web, allowing developers to specify the width of elements in a variety of ways. By combining keyword values, lengths, and global values, developers have fine-grained control over the width of their elements.