How to Make a Rectangle with CSS

Learn how to create a clean, scalable rectangle using pure CSS. Below you’ll find a live preview, copy-paste code, and quick tips to center content inside the shape.

Live Preview: Rectangle

Method 1: Fixed-Size Rectangle (width/height)

.rectangle {
  width: 140px;
  height: 100px;
  background-color: #cd5454;
}

Method 2: Responsive Rectangle (aspect-ratio)

.rectangle-responsive {
  /* Keeps a 3:2 rectangle at any width */
  aspect-ratio: 3 / 2;
  width: min(90vw, 320px);
  background-color: #cd5454;
}

How This Works

The fixed-size method uses explicit width and height to draw a rectangle, great for icons, badges, or UI elements with predictable dimensions.

The responsive method uses the aspect-ratio property to preserve shape while scaling with the container. Set a width, and the height is calculated automatically to keep the chosen ratio.

How to Center Content Inside a Rectangle

The easiest way is to turn the rectangle into a flex or grid container and center its children with a single line or two.

Method 1: Use CSS Flexbox

.rectangle {
  width: 140px;
  height: 100px;
  background-color: #cd5454;

  display: flex;
  justify-content: center;
  /* centers along the main axis (horizontal when flex-direction: row) */
  align-items: center; /* centers along the cross axis (vertical when flex-direction: row) */
}

Method 2: Use CSS Grid

.rectangle {
  width: 140px;
  height: 100px;
  background-color: #cd5454;

  display: grid;
  place-items: center; /* centers both axes */
}

When to Use Each Shape Method

Use fixed-size rectangles when you need pixel-perfect control (e.g., buttons, avatars). Use the aspect-ratio approach for fluid layouts that must scale across screens while maintaining a consistent shape ratio.

Quick Customizations

Change color by editing background-color (e.g., background-color: #cd5454;). Add a border with border: 2px solid #222; or slightly round the corners with border-radius: 6px for a softer look.

Accessibility & SEO

If the rectangle conveys meaning, provide an accessible name. Either include visible text inside the element, or assign an appropriate role (e.g., role=”img”) with aria-label or aria-labelledby. If it’s purely decorative, hide it from assistive technologies with aria-hidden=”true”. Also ensure sufficient color contrast between the rectangle and any text inside.