Box Model

Box Model


Every element on a webpage is a rectangular box that contains height, width, padding (internal), margin (external) and border that lies in between
The box model
The box model

Understanding Horizontal vs Vertical / XY

We can visualize horizontal (x) and vertical (y) using the illustration
We can visualize horizontal (x) and vertical (y) using the illustration

Properties

  • Box Model: margin, padding, border, fill-area (the area that gets painted when we set background color), height, width, and box-sizing: border-box border-radius to give roundness
  • Collapsing Margins happens when we set margin in Y axis. Means when two elements are given margins in vertical axis then only the bigger one gets applied
    • notion image

Padding/Margin Short-hands

  • The clockwise shorthand: padding: top right bottom left;
  • 3 Value shorthand: padding: top left/right bottom;
  • 2 Value shorthand: padding: top/bottom left/right;

Dimensions

  • Dimensions: height, width. If the height is fixed and content grows more then the height then the content overflows.
  • We can control the overflow behaviour using the overflow properties
    • Text overflowing from a fixed height box
      Text overflowing from a fixed height box
  • overflow-x, overflow-y, overflow: hidden/scroll/auto (which adapts)
  • min-height, min-width, max-height, max-width can help us with such issues

Background

.square { background-color: orange; background-image: url(""); background-size: cover/contain; object-fit: cover/contain; background-position: X Y; background-repeat: no-repeat/repeat; background-attachment: scroll/fixed; }
  • Shorthand: background: color image repeat attachment position;

Gradients

  • Gradients are transition from one color to another. We see a lot of gradients in Nature
  • There are three main types of gradients in CSS: linear, radial and conic
body { background-image: linear-gradient(to right, #000, #eee); }

Margin Top Issue

notion image
This is a weird bug where if we have a header inside a container and we try to give margin top to the header then the container will also go down
<div class="container"> <header> </header> </div>
To fix this we just add a little gap between the parent and the child and then child can take margin top freely
notion image