Back to topics

Basic CSS Gap Filling 1 (Box Model, Transparency, Min/Max Sizes, Colors)

1. box-sizing: Two Box Models

The default value of box-sizing is content-box. width/height only account for the content area, while padding and border are added outward.

div {
  width: 200px;
  padding: 20px;
  border: 5px solid black;
}
/* Actual occupied width = 200 + 20*2 + 5*2 = 250px */

Setting width to 200px results in an actual element width of 250px. Layout can be miscalculated.

box-sizing: border-box is more intuitive: width/height are calculated up to the border layer, and padding and border are squeezed inward.

div {
  box-sizing: border-box;
  width: 200px;
  padding: 20px;
  border: 5px solid black;
}
/* Actual content width = 200 - 20*2 - 5*2 = 150px */

border-box has become the industry standard. Almost all CSS frameworks (Bootstrap, Tailwind) and reset stylesheets include:

*, *::before, *::after {
  box-sizing: border-box;
}

2. Transparency: rgba and opacity

Both can make an element transparent, but their scope is completely different.

opacity makes the entire element transparent, affecting the element itself and all its children. Furthermore, child elements cannot override their own transparency; setting opacity: 1 on a child has no effect because the parent limits the overall transparency.

background: rgba() — only affects the background color. It only applies to this element's background, and the content remains unaffected. There are multiple ways to write rgba:

rgba(0, 0, 0, 0.5)
/* First three values for RGB separated by spaces, '/' followed by opacity */
rgb(0 0 0 / 50%)
/* (8-digit hex, first 6 digits are RGB) */
#00000000 

Another hidden difference: Stacking Context

An opacity value less than 1 creates a new stacking context, which can affect the behavior of z-index. rgba() does not.

3. Min and Max Sizes

Refers to four properties: max-height / min-height / max-width / min-width

When an element's dimensions change automatically (e.g., when set as a percentage, no width/height specified, or img affected by image pixels), setting min/max sizes prevents the element from becoming too small or too large.

In practical development, we usually set a minimum width for PC web pages. The typical value is 1200px ~ 1300px to prevent the PC window from shrinking indefinitely.

We often set a maximum width for images to avoid pixel dimensions breaking the layout.

4. Colors

If border is set without a color, it defaults to currentColor, which is equivalent to the text color.