CSS Programming Reference

CSS Programming Reference: Properties, Selectors & Examples

CSS Programming Reference

Why Understanding CSS Matters

CSS is what transforms basic HTML content into a visually organized, responsive website. It controls how elements appear on the page, including typography, colors, spacing, backgrounds, positioning, and layout across different screen sizes.

Understanding CSS fundamentals also makes it easier to customize WordPress websites, troubleshoot design issues, create responsive layouts, and work effectively with modern web design tools and frameworks.

Tech Prime Web

Key Insight

CSS controls the visual presentation and layout of web content. Together with HTML for structure and JavaScript for functionality, CSS is one of the core technologies used to build modern websites.

CSS Programming Reference

Whether you’re learning CSS or need a quick reference while working on a website, this guide covers essential CSS concepts used in modern web development. Browse the sections below for CSS comments, properties, selectors, layouts, responsive techniques, and practical examples.

CSS Comments

What Are CSS Comments?

CSS comments allow developers to add notes, explanations, and documentation directly inside a stylesheet without affecting how the browser displays the webpage. Comments are useful for organizing stylesheets, explaining complex rules, identifying sections, and temporarily disabling CSS during development or troubleshooting. Example:
/* This is a CSS comment */

CSS Comment Syntax

A CSS comment begins with a forward slash and an asterisk and ends with an asterisk followed by a forward slash. Example:
/* Comment goes here */
Comments can appear on their own line or alongside CSS declarations. Example:
.button {
    background-color: #ff6600; /* Primary button color */
    color: #ffffff;
}

Multi-Line CSS Comments

CSS comments can span multiple lines, making them useful for longer explanations or documentation. Example:
/*
This section contains
the primary navigation styles.
*/

.main-navigation {
    display: flex;
}

Organizing Stylesheets with Comments

Comments can be used as section labels to make large stylesheets easier to navigate and maintain. Example:
/* =========================
   HEADER
   ========================= */

.site-header {
    width: 100%;
}


/* =========================
   NAVIGATION
   ========================= */

.main-navigation {
    display: flex;
}


/* =========================
   FOOTER
   ========================= */

.site-footer {
    padding: 40px 0;
}

Temporarily Disabling CSS

Comments are also useful when testing or troubleshooting CSS. A declaration or group of declarations can be commented out without deleting the original code. Example:
.content {
    width: 100%;
    /* max-width: 1200px; */
    margin: 0 auto;
}
The browser ignores the commented declaration while continuing to process the remaining CSS.

CSS Comment Best Practices

Use comments when they help explain the purpose or organization of your CSS, especially in larger stylesheets or projects maintained by multiple developers. Avoid excessive comments that simply repeat what the CSS already makes clear. Comments are most useful for documenting unusual decisions, important dependencies, major stylesheet sections, or code that may otherwise be difficult to understand. Example:
/* Keep above modal overlay */
.site-header {
    position: relative;
    z-index: 1100;
}

CSS Properties

What Are CSS Properties?

CSS properties define how HTML elements are displayed and styled. Each property controls a specific aspect of an element, such as its color, size, spacing, border, background, typography, or position. A CSS declaration consists of a property followed by a colon and a value. Example:
p {
    color: #333333;
    font-size: 16px;
}
In this example, color and font-size are CSS properties, while #333333 and 16px are their values.

Color

The color property controls the color of text and other foreground content. Example:
p {
    color: #333333;
}

Background Color

The background-color property sets the background color of an element. Example:
.section {
    background-color: #f5f5f5;
}

Background Image

The background-image property displays an image as the background of an element. Example:
.hero {
    background-image: url("hero-background.jpg");
    background-size: cover;
    background-position: center;
}

Width

The width property controls the width of an element. Example:
.content {
    width: 100%;
}
For responsive layouts, width is often combined with max-width. Example:
.content {
    width: 100%;
    max-width: 1200px;
    margin: 0 auto;
}

Height

The height property sets the height of an element. Example:
.banner {
    height: 450px;
}
For responsive designs, fixed heights should be used carefully because content and screen sizes can vary.

Min-Width and Max-Width

The min-width and max-width properties define the minimum and maximum width an element can occupy. Example:
.container {
    width: 100%;
    max-width: 1200px;
}
Using max-width with a fluid width is a common technique for creating responsive content areas.

Min-Height and Max-Height

The min-height and max-height properties limit how short or tall an element can become. Example:
.hero {
    min-height: 500px;
}

Margin

The margin property controls the space outside an element, separating it from surrounding elements. Example:
.section {
    margin: 40px 20px;
}
The first value controls the top and bottom margins, while the second controls the left and right margins. Individual sides can also be specified. Example:
.section {
    margin-top: 40px;
    margin-right: 20px;
    margin-bottom: 40px;
    margin-left: 20px;
}

Padding

The padding property controls the space between an element's content and its border. Example:
.card {
    padding: 30px;
}
Different vertical and horizontal values can also be used. Example:
.card {
    padding: 30px 20px;
}

Border

The border property adds a visible boundary around an element and can define its width, style, and color. Example:
.card {
    border: 1px solid #dddddd;
}
Border properties can also be defined individually. Example:
.card {
    border-width: 1px;
    border-style: solid;
    border-color: #dddddd;
}

Border Radius

The border-radius property creates rounded corners. Example:
.card {
    border-radius: 10px;
}
A value of 50% is commonly used to create a circular element when its width and height are equal. Example:
.profile-image {
    width: 100px;
    height: 100px;
    border-radius: 50%;
}

Font Family

The font-family property specifies the typeface used to display text. Multiple fonts can be provided as fallbacks. Example:
body {
    font-family: Arial, Helvetica, sans-serif;
}

Font Size

The font-size property controls the size of text. Example:
h1 {
    font-size: 42px;
}
CSS supports several units for typography, including px, rem, em, and viewport-relative units.

Font Weight

The font-weight property controls the thickness or weight of text. Example:
h2 {
    font-weight: 700;
}
Common values include 400 for normal text and 700 for bold text, although available weights depend on the selected font.

Line Height

The line-height property controls the vertical spacing between lines of text. Example:
p {
    line-height: 1.6;
}
Unitless line-height values are commonly used because they scale with the element's font size.

Text Align

The text-align property controls the horizontal alignment of inline content within an element. Example:
.hero-title {
    text-align: center;
}
Common values include left, right, center, and justify.

Text Decoration

The text-decoration property adds or removes decorative lines from text. Example:
a {
    text-decoration: none;
}

a:hover {
    text-decoration: underline;
}

Display

The display property determines how an element participates in the page layout. Example:
.element {
    display: block;
}
Common display values include:
display: block;
display: inline;
display: inline-block;
display: none;
display: flex;
display: grid;
Flexbox and Grid are covered separately later in this reference.

Position

The position property determines how an element is positioned within the document. Common values include:
position: static;
position: relative;
position: absolute;
position: fixed;
position: sticky;
For example:
.header {
    position: sticky;
    top: 0;
}

Top, Right, Bottom, and Left

The top, right, bottom, and left properties can control the position of a positioned element. Example:
.badge {
    position: absolute;
    top: 10px;
    right: 10px;
}

Z-Index

The z-index property helps control the stacking order of overlapping positioned elements and certain other stacking contexts. Example:
.site-header {
    position: relative;
    z-index: 100;
}
A higher z-index can place an element above another element within the applicable stacking context.

Overflow

The overflow property determines what happens when content extends beyond an element's dimensions. Example:
.container {
    overflow: hidden;
}
Common values include visible, hidden, auto, scroll, and clip.

Opacity

The opacity property controls the transparency of an entire element. Example:
.overlay {
    opacity: 0.75;
}
Values range from 0, which is fully transparent, to 1, which is fully opaque.

Box Shadow

The box-shadow property adds one or more shadows around an element. Example:
.card {
    box-shadow: 0 4px 12px rgba(0, 0, 0, 0.15);
}

Box Sizing

The box-sizing property determines how an element's total width and height are calculated. Example:
*,
*::before,
*::after {
    box-sizing: border-box;
}
With border-box, declared width and height values include the element's padding and border, making layouts easier to manage.

Object Fit

The object-fit property controls how replaced content, such as an image or video, fits within its defined dimensions. Example:
.featured-image {
    width: 100%;
    height: 400px;
    object-fit: cover;
}
The cover value fills the available area while preserving the media's aspect ratio, which may crop part of the image.

Cursor

The cursor property controls the mouse pointer displayed when a user hovers over an element. Example:
.button {
    cursor: pointer;
}

Transition

The transition property creates a gradual change between property values when an element changes state. Example:
.button {
    transform: translateY(0);
    transition: transform 0.3s ease;
}

.button:hover {
    transform: translateY(-2px);
}

Transform

The transform property can move, rotate, scale, or skew an element without changing the normal document flow. Example:
.card:hover {
    transform: translateY(-5px);
}
Another example:
.icon {
    transform: rotate(45deg);
}

CSS Custom Properties

CSS custom properties, commonly called CSS variables, allow reusable values to be defined once and referenced throughout a stylesheet. Example:
:root {
    --primary-color: #0b2a55;
    --accent-color: #ff6600;
    --content-width: 1200px;
}

.button {
    background-color: var(--accent-color);
}

.container {
    max-width: var(--content-width);
}
Custom properties can make colors, spacing, typography, and other design values easier to maintain across a website.

CSS Selectors

What Are CSS Selectors?

CSS selectors identify the HTML elements that a CSS rule should style. Selectors can target elements by tag name, class, ID, attribute, state, position, or relationship to other elements. The basic structure of a CSS rule is:
selector {
    property: value;
}
For example:
p {
    color: #333333;
}
In this example, p is the selector and the color declaration is applied to matching paragraph elements.

Element Selector

An element selector, also called a type selector, targets HTML elements by their tag name. Example:
p {
    color: #333333;
}
This rule applies to all paragraph elements. Another example:
h2 {
    font-size: 32px;
}

Class Selector

A class selector targets elements containing a specific class attribute. Class selectors begin with a period. Example:
.button {
    padding: 12px 24px;
}
HTML:
Contact Us
Classes can be reused across multiple elements, making them useful for reusable components and styles.

ID Selector

An ID selector targets an element by its unique ID attribute. ID selectors begin with a hash symbol. Example:
#contact-form {
    max-width: 800px;
}
HTML:
...
An ID should uniquely identify an element within a webpage.

Universal Selector

The universal selector uses an asterisk and can match elements without requiring a specific tag, class, or ID. Example:
* {
    box-sizing: border-box;
}
A common implementation includes pseudo-elements:
*,
*::before,
*::after {
    box-sizing: border-box;
}

Grouping Selectors

Multiple selectors that share the same declarations can be grouped together using commas. Example:
h1,
h2,
h3 {
    font-weight: 700;
}
Grouping selectors helps reduce duplicated CSS.

Combining Element and Class Selectors

An element selector and class selector can be combined to target only elements of a specific type that contain the class. Example:
a.button {
    text-decoration: none;
}
This targets anchor elements with the button class. HTML:
Our Services

Multiple Class Selector

An element containing multiple classes can be targeted by placing the class selectors together without spaces. Example:
.button.primary {
    font-weight: 700;
}
HTML:
Contact Us
This rule applies only when both classes are present on the same element.

Descendant Selector

A descendant selector targets elements located anywhere inside another matching element. Example:
.content p {
    line-height: 1.6;
}
This targets paragraph elements located inside elements with the content class.

Child Selector

The child combinator uses the greater-than symbol to target direct children of an element. Example:
.navigation > li {
    margin-right: 20px;
}
Unlike a descendant selector, this only targets matching elements that are direct children.

Adjacent Sibling Selector

The adjacent sibling combinator uses a plus symbol to target an element immediately following another element. Example:
h2 + p {
    margin-top: 10px;
}
This targets a paragraph only when it immediately follows an h2 element.

General Sibling Selector

The general sibling combinator uses a tilde to target matching sibling elements that appear after another element. Example:
h2 ~ p {
    color: #555555;
}
This targets matching paragraph siblings appearing after the h2 within the same parent.

Attribute Selector

Attribute selectors target elements based on the presence or value of an HTML attribute. Example:
input[type="email"] {
    width: 100%;
}
This targets input elements whose type attribute is set to email.

Attribute Presence Selector

An attribute selector can target any element containing a particular attribute, regardless of its value. Example:
input[required] {
    border-color: #cc0000;
}
This targets input elements containing the required attribute.

Attribute Value Selectors

CSS provides several operators for matching portions of attribute values. Exact value:
a[target="_blank"] {
    text-decoration: underline;
}
Value begins with:
a[href^="https://"] {
    font-weight: 600;
}
Value ends with:
a[href$=".pdf"] {
    text-decoration: underline;
}
Value contains:
a[href*="techprimeweb"] {
    font-weight: 700;
}

Pseudo-Class Selector

Pseudo-classes target elements based on a state, position, user interaction, or other condition. They begin with a colon. A common example is the hover state:
a:hover {
    text-decoration: underline;
}

Hover Pseudo-Class

The :hover pseudo-class applies styles when a pointing device is positioned over an element. Example:
.button:hover {
    transform: translateY(-2px);
}

Focus Pseudo-Class

The :focus pseudo-class targets an element when it receives focus. Example:
input:focus {
    border-color: #333333;
}

Focus-Visible Pseudo-Class

The :focus-visible pseudo-class can provide visible focus indicators when the browser determines that a focus indicator should be shown, such as during keyboard navigation. Example:
a:focus-visible,
button:focus-visible {
    outline: 2px solid currentColor;
    outline-offset: 3px;
}
Visible focus indicators are important for keyboard accessibility.

First-Child and Last-Child

The :first-child and :last-child pseudo-classes target an element based on its position among sibling elements. Example:
li:first-child {
    font-weight: 700;
}

li:last-child {
    margin-bottom: 0;
}

Nth-Child Selector

The :nth-child() pseudo-class targets elements based on their position among siblings. Example:
tr:nth-child(even) {
    background-color: #f5f5f5;
}
It can also target specific positions:
.card:nth-child(3) {
    margin-right: 0;
}

Not Selector

The :not() pseudo-class excludes elements that match the selector provided inside it. Example:
.navigation a:not(.button) {
    text-decoration: none;
}
This targets navigation links except those containing the button class.

Is Selector

The :is() pseudo-class allows multiple selectors to be grouped within part of a larger selector. Example:
.content :is(h2, h3, h4) {
    font-weight: 700;
}
This can make complex selector groups shorter and easier to maintain.

Where Selector

The :where() pseudo-class works similarly to :is(), but the :where() selector itself and its arguments contribute zero specificity. Example:
:where(.content, .sidebar) a {
    text-decoration: underline;
}
This can be useful when creating styles that should remain easy to override.

Has Selector

The :has() relational pseudo-class can select an element based on elements or conditions relative to it. Example:
.card:has(img) {
    padding-top: 0;
}
This targets cards that contain an image. Another example:
form:has(input:invalid) {
    border-color: #cc0000;
}

Pseudo-Element Selector

Pseudo-elements target a specific part of an element or allow generated content to be styled. They are commonly written with two colons. Common pseudo-elements include:
::before
::after
::first-letter
::first-line
::selection

Before and After Pseudo-Elements

The ::before and ::after pseudo-elements can create generated content associated with an element. Example:
.heading::after {
    content: "";
    display: block;
    width: 50px;
    height: 2px;
    margin-top: 10px;
}
Generated content should generally be decorative rather than essential information that users must access.

Selector Best Practices

Use selectors that are clear, reusable, and easy to maintain. Class selectors are commonly preferred for reusable components because they can be applied consistently without creating unnecessary specificity. Avoid overly complex selectors such as:
body #page .content div.card p.title {
    font-weight: 700;
}
A simpler reusable class is usually easier to maintain:
.card-title {
    font-weight: 700;
}
Keeping selectors simple also makes future CSS changes and troubleshooting easier.

CSS Flexbox

What Is CSS Flexbox?

CSS Flexbox, or the Flexible Box Layout, is a layout system designed to arrange elements in a row or column while providing control over alignment, spacing, sizing, and distribution. Flexbox is especially useful for navigation menus, card layouts, button groups, columns, and components that need flexible alignment. To create a flex container, set the display property to flex. Example:
.container {
    display: flex;
}
The direct children of the container become flex items.

Flex Direction

The flex-direction property determines the direction in which flex items are arranged. Example:
.container {
    display: flex;
    flex-direction: row;
}
Common values include:
flex-direction: row;
flex-direction: row-reverse;
flex-direction: column;
flex-direction: column-reverse;
The default value is row.

Justify Content

The justify-content property controls how flex items are positioned and distributed along the main axis of the flex container. Example:
.container {
    display: flex;
    justify-content: space-between;
}
Common values include:
justify-content: flex-start;
justify-content: center;
justify-content: flex-end;
justify-content: space-between;
justify-content: space-around;
justify-content: space-evenly;

Align Items

The align-items property controls how flex items are aligned along the cross axis. Example:
.container {
    display: flex;
    align-items: center;
}
Common values include:
align-items: stretch;
align-items: flex-start;
align-items: center;
align-items: flex-end;
align-items: baseline;

Gap

The gap property defines spacing between flex items without requiring margins on the individual items. Example:
.container {
    display: flex;
    gap: 24px;
}
Different row and column gaps can also be specified. Example:
.container {
    display: flex;
    row-gap: 20px;
    column-gap: 30px;
}

Flex Wrap

By default, flex items attempt to remain on a single line. The flex-wrap property allows items to move onto additional lines when necessary. Example:
.cards {
    display: flex;
    flex-wrap: wrap;
    gap: 30px;
}
Common values include:
flex-wrap: nowrap;
flex-wrap: wrap;
flex-wrap: wrap-reverse;

Flex Grow

The flex-grow property determines how much a flex item can grow relative to other flex items when additional space is available. Example:
.column {
    flex-grow: 1;
}
If multiple items have the same flex-grow value, available space is distributed proportionally among them. Example:
.column-one {
    flex-grow: 1;
}

.column-two {
    flex-grow: 2;
}
In this example, the second item can receive twice as much of the available growth space as the first.

Flex Shrink

The flex-shrink property determines how a flex item can shrink when there is not enough available space in the container. Example:
.logo {
    flex-shrink: 0;
}
Setting flex-shrink to 0 prevents the item from shrinking as part of flex sizing.

Flex Basis

The flex-basis property specifies the initial main size of a flex item before remaining space is distributed. Example:
.card {
    flex-basis: 300px;
}

Flex Shorthand

The flex property combines flex-grow, flex-shrink, and flex-basis into one declaration. Example:
.column {
    flex: 1 1 300px;
}
This represents:
flex-grow: 1;
flex-shrink: 1;
flex-basis: 300px;
A common shorthand is:
.column {
    flex: 1;
}
The exact computed longhand values of shorthand declarations should be considered when more precise sizing behavior is required.

Align Self

The align-self property allows an individual flex item to override the align-items setting of its flex container. Example:
.featured-card {
    align-self: flex-start;
}

Order

The order property changes the visual order of flex items. Example:
.first-column {
    order: 2;
}

.second-column {
    order: 1;
}
This changes the visual presentation without changing the source order of the HTML. Use order carefully because visual order that differs from the underlying document order can create confusing experiences for keyboard and assistive technology users.

Centering Content with Flexbox

Flexbox provides a simple way to center content horizontally and vertically. Example:
.hero-content {
    display: flex;
    justify-content: center;
    align-items: center;
    min-height: 500px;
}

Equal-Width Columns

Flexbox can create columns that share available space equally. Example:
.row {
    display: flex;
    gap: 30px;
}

.column {
    flex: 1;
}
Each column receives an equal share of the available flex space.

Responsive Flexbox Layout

Flexbox can be combined with media queries to change the layout on smaller screens. Example:
.row {
    display: flex;
    gap: 30px;
}

.column {
    flex: 1;
}

@media (max-width: 768px) {
    .row {
        flex-direction: column;
    }
}
The layout displays columns horizontally on larger screens and stacks them vertically on smaller screens.

Common Flexbox Layout

A common card layout uses flex-wrap and gap to create a flexible row of cards. Example:
.cards {
    display: flex;
    flex-wrap: wrap;
    gap: 30px;
}

.card {
    flex: 1 1 300px;
}
Each card starts with a preferred flex basis of 300px and can grow or shrink as available space changes.

Flexbox Best Practices

Use Flexbox when the layout primarily needs to organize content along one dimension, such as a row or column. Flexbox works particularly well for alignment, navigation, equal-height components, button groups, and layouts where items need to grow, shrink, or wrap based on available space. For layouts that require stronger control over both rows and columns at the same time, CSS Grid may be a better choice.

CSS Grid

What Is CSS Grid?

CSS Grid Layout is a two-dimensional layout system designed to organize content into rows and columns. It provides precise control over page layouts, card grids, galleries, content sections, and other structured designs. To create a grid container, set the display property to grid. Example:
.grid {
    display: grid;
}
The direct children of the container become grid items.

Grid Template Columns

The grid-template-columns property defines the number and size of columns in a grid. Example:
.grid {
    display: grid;
    grid-template-columns: 1fr 1fr 1fr;
}
This creates three equal-width columns. The repeat() function provides a shorter way to write the same layout. Example:
.grid {
    display: grid;
    grid-template-columns: repeat(3, 1fr);
}

Grid Template Rows

The grid-template-rows property defines the size of explicitly created grid rows. Example:
.grid {
    display: grid;
    grid-template-rows: 150px 300px;
}
This creates a first row that is 150 pixels high and a second row that is 300 pixels high.

The fr Unit

The fr unit represents a fraction of the available space inside a grid container. Example:
.grid {
    display: grid;
    grid-template-columns: 1fr 2fr;
}
In this example, the second track receives twice the fractional share of available grid space as the first.

Grid Gap

The gap property controls spacing between grid rows and columns. Example:
.grid {
    display: grid;
    grid-template-columns: repeat(3, 1fr);
    gap: 30px;
}
Row and column spacing can also be controlled separately. Example:
.grid {
    row-gap: 20px;
    column-gap: 30px;
}

Responsive Grid with Minmax

The minmax() function defines a minimum and maximum size for a grid track. Combined with repeat() and auto-fit, it can create responsive layouts without requiring a media query for every screen size. Example:
.grid {
    display: grid;
    grid-template-columns: repeat(auto-fit, minmax(250px, 1fr));
    gap: 30px;
}
Each column remains at least 250 pixels wide when possible and can expand to share available space.

Auto-Fit

The auto-fit keyword can create as many tracks as will fit within the available grid space and allows empty tracks to collapse. Example:
.grid {
    display: grid;
    grid-template-columns: repeat(auto-fit, minmax(250px, 1fr));
}
This is useful for responsive card layouts where the number of visible columns changes with the available width.

Auto-Fill

The auto-fill keyword creates as many grid tracks as can fit within the available space, including empty tracks when applicable. Example:
.grid {
    display: grid;
    grid-template-columns: repeat(auto-fill, minmax(250px, 1fr));
}
The difference between auto-fill and auto-fit becomes most noticeable when the container has room for more columns than there are grid items.

Grid Column

The grid-column property controls where a grid item begins and ends across grid columns. Example:
.featured {
    grid-column: 1 / 3;
}
This item spans from grid line 1 to grid line 3. An item can also span a specified number of columns. Example:
.featured {
    grid-column: span 2;
}

Grid Row

The grid-row property controls where a grid item begins and ends across grid rows. Example:
.sidebar {
    grid-row: 1 / 3;
}
A span can also be used. Example:
.sidebar {
    grid-row: span 2;
}

Grid Column Start and End

The starting and ending grid lines can be specified separately. Example:
.content {
    grid-column-start: 1;
    grid-column-end: 3;
}
This is equivalent to:
.content {
    grid-column: 1 / 3;
}

Grid Template Areas

The grid-template-areas property allows areas of a layout to be assigned descriptive names. Example:
.page-layout {
    display: grid;
    grid-template-columns: 250px 1fr;
    grid-template-areas:
        "sidebar content";
}

.sidebar {
    grid-area: sidebar;
}

.content {
    grid-area: content;
}
Named grid areas can make larger layouts easier to understand and maintain.

Justify Items

The justify-items property controls how grid items are aligned along the inline axis within their grid areas. Example:
.grid {
    display: grid;
    justify-items: center;
}
Common values include:
justify-items: start;
justify-items: center;
justify-items: end;
justify-items: stretch;

Align Items

The align-items property controls how grid items are aligned along the block axis within their grid areas. Example:
.grid {
    display: grid;
    align-items: center;
}

Place Items

The place-items property is a shorthand for align-items and justify-items. Example:
.grid {
    display: grid;
    place-items: center;
}
This centers grid items along both axes within their grid areas.

Justify Content

The justify-content property controls the alignment and distribution of the entire grid when the grid is smaller than its container along the inline axis. Example:
.grid {
    display: grid;
    justify-content: center;
}

Align Content

The align-content property controls the alignment and distribution of grid tracks along the block axis when additional space is available. Example:
.grid {
    display: grid;
    align-content: center;
}

Grid Auto Rows

The grid-auto-rows property defines the size of automatically created rows. Example:
.grid {
    display: grid;
    grid-auto-rows: minmax(150px, auto);
}
Automatically created rows will be at least 150 pixels high and can grow when their content requires additional space.

Grid Auto Flow

The grid-auto-flow property controls how automatically placed grid items are inserted into the grid. Example:
.grid {
    display: grid;
    grid-auto-flow: row;
}
Common values include:
grid-auto-flow: row;
grid-auto-flow: column;
grid-auto-flow: dense;
The dense value can attempt to fill earlier gaps in the grid, which may cause items to appear visually out of source order.

Two-Column Layout

A common content and sidebar layout can be created with Grid. Example:
.page-layout {
    display: grid;
    grid-template-columns: 2fr 1fr;
    gap: 40px;
}
The main content receives two fractional shares of the available track space while the sidebar receives one.

Responsive Two-Column Layout

A grid layout can be combined with a media query to stack columns on smaller screens. Example:
.page-layout {
    display: grid;
    grid-template-columns: 2fr 1fr;
    gap: 40px;
}

@media (max-width: 768px) {
    .page-layout {
        grid-template-columns: 1fr;
    }
}
The layout uses two columns on larger screens and a single column on smaller screens.

Responsive Card Grid

CSS Grid can create a flexible card layout with very little code. Example:
.cards {
    display: grid;
    grid-template-columns: repeat(auto-fit, minmax(280px, 1fr));
    gap: 30px;
}
The browser automatically adjusts the number of columns based on the available width and the minimum card size.

CSS Grid vs. Flexbox

CSS Grid and Flexbox are complementary layout systems. Flexbox is especially useful when arranging and aligning items primarily along one dimension, such as a row or column. CSS Grid is especially useful when a layout requires coordinated control over rows and columns. A website can use both. For example, Grid may define the overall card layout while Flexbox controls the alignment of content inside each card.

CSS Grid Best Practices

Use CSS Grid when content benefits from a structured row-and-column layout. Functions such as repeat(), minmax(), and auto-fit can create flexible layouts that adapt to available space with fewer breakpoint-specific rules. Keep the underlying HTML in a logical order whenever possible. Visual placement should support the document structure rather than make the visual experience substantially different from the source order.

Responsive CSS

What Is Responsive CSS?

Responsive CSS allows a website to adapt its layout, typography, images, and interface elements to different screen sizes and available spaces. A responsive website should remain usable and visually consistent across desktop computers, laptops, tablets, and mobile devices without requiring a separate version of the website.

Media Queries

Media queries apply CSS rules when specific conditions are met, such as when the viewport reaches a certain width. Example:
@media (max-width: 768px) {
    .content {
        padding: 20px;
    }
}
In this example, the padding is applied when the viewport width is 768 pixels or less.

Responsive Breakpoints

Breakpoints are conditions where a layout changes to better fit the available space. Example:
.grid {
    display: grid;
    grid-template-columns: repeat(3, 1fr);
    gap: 30px;
}

@media (max-width: 1024px) {
    .grid {
        grid-template-columns: repeat(2, 1fr);
    }
}

@media (max-width: 768px) {
    .grid {
        grid-template-columns: 1fr;
    }
}
This layout displays three columns on larger screens, two columns at narrower widths, and one column on smaller screens. Breakpoints should generally be chosen based on when the content or layout needs to change rather than targeting individual device models.

Mobile-First CSS

A mobile-first approach begins with styles for smaller screens and adds layout enhancements as more space becomes available. Example:
.cards {
    display: grid;
    grid-template-columns: 1fr;
    gap: 20px;
}

@media (min-width: 768px) {
    .cards {
        grid-template-columns: repeat(2, 1fr);
    }
}

@media (min-width: 1200px) {
    .cards {
        grid-template-columns: repeat(3, 1fr);
    }
}
This approach uses min-width media queries to progressively enhance the layout for larger screens.

Fluid Widths

Fluid layouts use relative sizing so elements can expand or contract with their available space. Example:
.container {
    width: 100%;
    max-width: 1200px;
    margin: 0 auto;
}
The container can use the available width while max-width prevents it from becoming excessively wide on larger screens.

Relative CSS Units

Relative units can make layouts and typography more adaptable than relying exclusively on fixed pixel values. Common responsive units include:
%
em
rem
vw
vh
dvw
dvh
For example:
.content {
    width: 90%;
    max-width: 1200px;
}
The percentage width responds to the available width while max-width establishes an upper limit.

Responsive Typography with Clamp

The clamp() function can create fluid values that scale within defined minimum and maximum limits. Example:
h1 {
    font-size: clamp(2rem, 5vw, 4rem);
}
The first value defines the minimum size, the middle value provides the preferred fluid size, and the final value defines the maximum size. Clamp can also be useful for responsive spacing. Example:
.section {
    padding-block: clamp(40px, 6vw, 100px);
}

Responsive Images

Images should generally adapt to the width of their containers without exceeding their natural layout space. Example:
img {
    max-width: 100%;
    height: auto;
}
The max-width prevents an image from overflowing its container, while height: auto preserves its aspect ratio.

Responsive Background Images

Background images can be configured to fill an area while maintaining their proportions. Example:
.hero {
    background-image: url("hero.jpg");
    background-size: cover;
    background-position: center;
    background-repeat: no-repeat;
}
The cover value fills the background area while maintaining the image's aspect ratio, which may crop portions of the image.

Responsive Video and Embedded Content

Embedded media can use the aspect-ratio property to maintain its proportions as the container changes size. Example:
.video {
    width: 100%;
    aspect-ratio: 16 / 9;
}

.video iframe {
    width: 100%;
    height: 100%;
    border: 0;
}
This allows the embedded content to scale while maintaining a 16:9 aspect ratio.

Responsive Flexbox

Flexbox layouts can change direction when less horizontal space is available. Example:
.row {
    display: flex;
    gap: 30px;
}

.column {
    flex: 1;
}

@media (max-width: 768px) {
    .row {
        flex-direction: column;
    }
}
The columns display side by side on larger screens and stack vertically on smaller screens.

Responsive CSS Grid

CSS Grid can create responsive layouts without requiring a breakpoint for every layout change. Example:
.cards {
    display: grid;
    grid-template-columns: repeat(auto-fit, minmax(250px, 1fr));
    gap: 30px;
}
The browser adjusts the number of columns according to the available space while maintaining the minimum track size when possible.

Container Queries

Container queries allow a component to respond to the size of a containing element rather than only the size of the browser viewport. First, establish a query container:
.card-wrapper {
    container-type: inline-size;
}
Then apply styles based on the container's available inline size:
@container (min-width: 500px) {
    .card {
        display: grid;
        grid-template-columns: 1fr 2fr;
        gap: 20px;
    }
}
Container queries are useful for reusable components that may appear in different areas and widths throughout a website.

Orientation Media Query

Media queries can respond to the orientation of the viewport. Example:
@media (orientation: landscape) {
    .hero {
        min-height: 70vh;
    }
}
Orientation should generally be used when the design genuinely benefits from a different layout rather than as a substitute for width-based responsive design.

Hover Capability

CSS can detect whether the primary input mechanism can conveniently hover over elements. Example:
@media (hover: hover) {
    .card:hover {
        transform: translateY(-4px);
    }
}
This can help avoid relying on hover-specific effects on devices where hovering is unavailable or inconvenient.

Reduced Motion

The prefers-reduced-motion media feature allows a website to respect a user's preference for reduced non-essential motion. Example:
@media (prefers-reduced-motion: reduce) {
    *,
    *::before,
    *::after {
        scroll-behavior: auto;
        transition-duration: 0.01ms;
        animation-duration: 0.01ms;
        animation-iteration-count: 1;
    }
}
Reduced-motion preferences should be considered when implementing animations, transitions, parallax effects, and other motion-heavy interfaces.

Responsive Navigation

Navigation layouts often need to adapt when horizontal space becomes limited. Example:
.navigation {
    display: flex;
    gap: 24px;
}

@media (max-width: 768px) {
    .navigation {
        flex-direction: column;
        gap: 12px;
    }
}
For complex mobile navigation, CSS is often combined with accessible HTML and JavaScript to control expandable menus and interaction states.

Responsive CSS Best Practices

Responsive design should be based on the needs of the content rather than a fixed list of devices. Use flexible layouts, responsive images, relative sizing, Flexbox, Grid, media queries, and container queries where appropriate. Test layouts at multiple widths, including sizes between common breakpoints. Content should remain readable, navigation should remain usable, and interactive elements should have sufficient space for touch and keyboard interaction. Avoid creating separate desktop and mobile content when the same semantic content can adapt through responsive layout techniques.

CSS Specificity

What Is CSS Specificity?

CSS specificity is part of the cascade that helps determine which competing CSS declaration applies when multiple rules target the same element. Selectors with greater specificity generally take precedence over selectors with lower specificity when the competing declarations otherwise have the same cascade origin, importance, and layer. Example:
p {
    color: #333333;
}

.content p {
    color: #0066cc;
}
For paragraph elements inside .content, the second selector has greater specificity and its color declaration will apply when no higher-priority cascade rule overrides it.

Specificity Categories

Specificity is determined by the selectors used in a rule. A practical way to understand it is to consider three main categories:
ID selectors
Class, attribute, and pseudo-class selectors
Element and pseudo-element selectors
ID selectors carry more specificity than class-level selectors, while class-level selectors carry more specificity than element selectors. The universal selector and :where() do not add specificity.

Element Selector Specificity

Element selectors contribute to the element portion of specificity. Example:
p {
    color: #333333;
}
Another example:
main p {
    color: #444444;
}
The second selector contains two element selectors and therefore has greater specificity than a selector containing only p.

Class Selector Specificity

Class selectors have greater specificity than element selectors. Example:
p {
    color: #333333;
}

.intro {
    color: #0066cc;
}
If a paragraph has the intro class, the .intro declaration takes precedence when the other cascade factors are equal.

Attribute Selector Specificity

Attribute selectors contribute to specificity at the same category as class selectors. Example:
input {
    border-color: #cccccc;
}

input[required] {
    border-color: #cc0000;
}
The second selector is more specific because it contains both an element selector and an attribute selector.

Pseudo-Class Specificity

Most pseudo-classes contribute to the same specificity category as classes and attributes. Example:
a {
    text-decoration: none;
}

a:hover {
    text-decoration: underline;
}
The :hover pseudo-class adds specificity to the second selector.

ID Selector Specificity

ID selectors carry greater specificity than class, attribute, pseudo-class, and element selectors. Example:
.contact-form {
    max-width: 1000px;
}

#contact-form {
    max-width: 800px;
}
If both selectors target the same element and the other cascade factors are equal, the ID selector takes precedence.

Combining Selectors

Specificity increases as qualifying selectors are combined. Example:
.card p {
    color: #555555;
}

.card .description {
    color: #333333;
}
The second selector contains two class selectors, while the first contains one class selector and one element selector. The second therefore has greater specificity.

Source Order

When competing declarations have equal specificity and the other relevant cascade factors are equal, the declaration that appears later takes precedence. Example:
.button {
    background-color: #333333;
}

.button {
    background-color: #0066cc;
}
In this example, the second background-color declaration applies because both selectors have equal specificity and it appears later.

Inline Styles

Inline styles are declarations written directly in an element's style attribute and have high priority within the normal author cascade. Example:

Important Message

Inline styles can make sitewide styling harder to maintain and should generally be avoided when reusable stylesheet rules can accomplish the same result.

The !important Declaration

The !important flag changes the priority of a declaration within the cascade. Example:
.button {
    background-color: #0066cc !important;
}
Important declarations take precedence over normal declarations from the same origin and cascade layer, but !important does not eliminate the cascade. Competing important declarations are still resolved according to cascade rules. Avoid using !important as a routine solution to specificity problems. Excessive use can make CSS difficult to override, maintain, and troubleshoot.

Specificity and :is()

The :is() pseudo-class itself does not add specificity. Its specificity is determined by the most specific selector in its selector list. Example:
:is(.content, .sidebar) p {
    line-height: 1.6;
}
Understanding this behavior is important when :is() contains selectors with substantially different specificity.

Specificity and :not()

The :not() pseudo-class follows a similar specificity rule. The :not() itself does not add specificity, but the most specific selector in its argument list contributes to the selector's specificity. Example:
.navigation a:not(.button) {
    text-decoration: none;
}

Specificity and :has()

The :has() pseudo-class also takes specificity from the most specific selector in its argument list. Example:
.card:has(.featured-image) {
    padding-top: 0;
}
In this example, both .card and .featured-image contribute class-level specificity.

Zero Specificity with :where()

The :where() pseudo-class and all selectors inside it contribute zero specificity. Example:
:where(.content, .sidebar) a {
    text-decoration: underline;
}
This makes :where() useful for defining broad default styles that remain easy to override later.

Specificity and Cascade Layers

Cascade layers allow groups of CSS rules to be assigned an explicit order in the cascade. Example:
@layer reset, base, components, utilities;

@layer components {
    .button {
        padding: 12px 24px;
    }
}
For normal declarations in author layers, declarations in a later layer take precedence over declarations in earlier layers before selector specificity is compared between those layers. This can help reduce the need for increasingly specific selectors when organizing larger stylesheets.

Avoid Overly Specific Selectors

Selectors that contain many IDs, classes, and elements can become difficult to override and maintain. Avoid patterns such as:
body #page .content .cards div.card p.card-title {
    font-weight: 700;
}
Prefer a reusable class when possible:
.card-title {
    font-weight: 700;
}
Simpler selectors make stylesheets easier to understand and reduce specificity conflicts.

Specificity Best Practices

Keep specificity as low and predictable as practical. Use reusable class selectors for components, avoid unnecessary IDs for styling, and keep selector chains short. Before adding !important or creating a more complex selector, identify why the existing rule is winning. The issue may involve source order, inheritance, cascade layers, inline styles, or another part of the cascade rather than specificity alone. A consistent CSS architecture makes styles easier to override, troubleshoot, and maintain as a website grows.

CSS Best Practices

Write Clear and Maintainable CSS

Well-organized CSS is easier to understand, troubleshoot, update, and reuse. As a website grows, consistent styling practices help prevent unnecessary duplication and conflicting rules. Use descriptive selectors and organize related styles together. Example:
.service-card {
    padding: 30px;
}

.service-card-title {
    font-weight: 700;
}

.service-card-description {
    line-height: 1.6;
}

Use Reusable Classes

Reusable classes allow the same styling to be applied to multiple elements without duplicating CSS. Example:
.button {
    display: inline-block;
    padding: 12px 24px;
    text-decoration: none;
}
The same class can then be used throughout the website.
Our Services

Contact Us

Use Consistent Naming

Choose class names that describe the purpose or role of a component rather than its temporary appearance. Instead of:
.blue-box {
    padding: 30px;
}
Consider:
.service-card {
    padding: 30px;
}
A descriptive component name remains meaningful even if the design changes later.

Keep Selectors Simple

Avoid unnecessarily long selector chains that increase specificity and make styles difficult to override. Instead of:
body #page .content div.services div.card h3.title {
    font-weight: 700;
}
Prefer:
.service-card-title {
    font-weight: 700;
}
Simple selectors are generally easier to maintain and troubleshoot.

Avoid Unnecessary !important

The !important flag can be useful in limited situations, but it should not be the default solution for overriding styles. Before using !important, determine whether the issue can be resolved by improving selector structure, source order, cascade layers, or the organization of the stylesheet. Avoid:
.button {
    background-color: #0066cc !important;
}
When a normal declaration is sufficient:
.primary-button {
    background-color: #0066cc;
}

Use CSS Custom Properties

CSS custom properties can centralize reusable values such as colors, spacing, typography, and layout dimensions. Example:
:root {
    --primary-color: #0b2a55;
    --accent-color: #ff6600;
    --text-color: #333333;
    --content-width: 1200px;
    --section-spacing: 80px;
}
These values can then be reused throughout the stylesheet.
.container {
    max-width: var(--content-width);
}

.button {
    background-color: var(--accent-color);
}

.section {
    padding-block: var(--section-spacing);
}
Changing the custom property can update every rule that references it.

Use Flexbox and Grid for Layout

Flexbox and CSS Grid provide modern tools for building responsive layouts without relying on older techniques such as floats for general page layout. Flexbox works well for one-dimensional alignment:
.navigation {
    display: flex;
    align-items: center;
    gap: 24px;
}
Grid works well for structured rows and columns:
.cards {
    display: grid;
    grid-template-columns: repeat(3, 1fr);
    gap: 30px;
}

Build Responsive Layouts

Avoid designing CSS for only one screen size. Layouts should adapt to the available space while keeping content readable and controls usable. Example:
.cards {
    display: grid;
    grid-template-columns: repeat(auto-fit, minmax(250px, 1fr));
    gap: 30px;
}
Media queries and container queries can provide additional control when a component needs a specific layout adjustment.

Avoid Unnecessary Fixed Dimensions

Fixed widths and heights can cause content to overflow or create layout problems on smaller screens. Instead of relying on a fixed width:
.content {
    width: 1200px;
}
A responsive approach may use:
.content {
    width: 100%;
    max-width: 1200px;
    margin: 0 auto;
}
Use fixed dimensions when the design requires them, but consider how the element behaves when content or available space changes.

Use the Border-Box Model

The border-box value makes sizing easier to manage because an element's declared width and height include its padding and border. A common sitewide rule is:
*,
*::before,
*::after {
    box-sizing: border-box;
}
This creates more predictable element sizing across layouts.

Keep Accessibility in Mind

CSS should support the usability and accessibility of the underlying HTML rather than hide important states or information. For example, interactive elements should provide a visible keyboard focus indicator.
a:focus-visible,
button:focus-visible {
    outline: 2px solid currentColor;
    outline-offset: 3px;
}
Avoid removing focus outlines unless an accessible replacement is provided.

Do Not Rely on Color Alone

Color can communicate meaning, but important states should not depend exclusively on color. For example, an error field can combine color with a border and explanatory message.
.field-error {
    border: 2px solid #b00020;
}
The HTML should also provide meaningful text or other appropriate information describing the error.

Respect Reduced Motion Preferences

Animations and transitions should consider users who prefer reduced motion. Example:
@media (prefers-reduced-motion: reduce) {
    *,
    *::before,
    *::after {
        scroll-behavior: auto;
        transition-duration: 0.01ms;
        animation-duration: 0.01ms;
        animation-iteration-count: 1;
    }
}
Motion should enhance the interface without making the website difficult to use.

Use Comments Where They Add Value

Comments can document important decisions, organize sections, or explain code that may not be immediately obvious. Example:
/* Keep header above the off-canvas overlay */
.site-header {
    position: relative;
    z-index: 1100;
}
Avoid adding comments that simply repeat what a straightforward CSS declaration already communicates.

Avoid Repeating the Same Styles

When several elements use the same styling, consider creating a reusable class or grouping selectors. Instead of:
.service-button {
    padding: 12px 24px;
}

.contact-button {
    padding: 12px 24px;
}
Use:
.button {
    padding: 12px 24px;
}
Reducing unnecessary duplication makes future changes easier to manage.

Organize Stylesheets Logically

A consistent stylesheet structure makes CSS easier to navigate. For example:
/* Base Styles */

/* Typography */

/* Layout */

/* Header */

/* Navigation */

/* Components */

/* Forms */

/* Footer */

/* Responsive Styles */
The exact structure can vary by project, but consistency is more important than following one universal organization method.

Consider Browser Compatibility

Modern CSS continues to evolve. Before relying on newer features for essential functionality, verify that they are supported by the browsers required for the project. Progressive enhancement can allow modern browsers to use newer capabilities while maintaining a functional experience elsewhere. The @supports rule can test for CSS feature support. Example:
@supports (display: grid) {
    .cards {
        display: grid;
        grid-template-columns: repeat(3, 1fr);
    }
}

Remove Unused CSS Carefully

Unused CSS can increase stylesheet size and make a website harder to maintain. Periodically review styles that are no longer required. Be careful with automated removal tools because some classes may be generated dynamically by WordPress, themes, plugins, JavaScript, or page builders and may not appear directly in static HTML.

Optimize CSS for Performance

Keep stylesheets organized and avoid unnecessary duplication. Production websites can also benefit from CSS minification and appropriate caching. Performance optimization should be tested carefully, particularly on WordPress websites where themes, plugins, page builders, and optimization tools may each modify or combine CSS.

Test CSS Across Screen Sizes

Test layouts at desktop, tablet, and mobile widths, including sizes between established breakpoints. Check typography, spacing, navigation, forms, buttons, images, grids, and interactive states to make sure the design remains usable as the available space changes.

CSS Best Practice Summary

Effective CSS should be readable, reusable, responsive, accessible, and maintainable. Keep selectors simple, use modern layout systems, minimize unnecessary overrides, and organize styles so future changes can be made without creating additional conflicts. CSS should work together with semantic HTML to create websites that adapt reliably across devices while remaining easy to maintain as the project evolves.

Frequently Asked Questions About CSS

CSS stands for Cascading Style Sheets. It is a stylesheet language used to control the visual presentation of HTML content, including colors, typography, spacing, backgrounds, borders, and page layouts.
CSS is used to control how web content appears across different devices and screen sizes. It can define typography, colors, spacing, positioning, responsive layouts, animations, and many other visual aspects of a website.
HTML provides the structure and meaning of web content, while CSS controls how that content is presented. HTML defines elements such as headings, paragraphs, links, images, and forms, while CSS determines their appearance and layout.
CSS properties define the characteristics that can be styled on an element. Examples include color, font-size, margin, padding, background-color, display, and border.
CSS selectors identify which HTML elements should receive specific styles. Selectors can target elements by tag name, class, ID, attribute, state, position, or relationship to other elements.
The CSS box model describes how an element is represented as a rectangular box consisting of its content, padding, border, and margin. Understanding the box model is important for controlling element dimensions and spacing.
Flexbox is primarily designed for arranging and aligning content along one dimension, such as a row or column. CSS Grid provides two-dimensional control over rows and columns. They can also be used together within the same website.
Media queries allow CSS rules to be applied when specified conditions are met, such as a particular viewport width. They are commonly used to adjust layouts, typography, navigation, and other elements for different screen sizes.
Tech Prime Web

About Tech Prime Web

We help businesses grow with data-driven SEO, AEO and digital marketing strategies that improve visibility, increase traffic and generate real results.

Share This Story, Choose Your Platform!