🐘

CSS

12 notes  •  PHP & Web Dev

Disable Anchor Tag Clicks with CSS

You can prevent a link from behaving like a link — doing nothing when clicked — using the CSS pointer-events property. This is useful when you want to deactivate navigation links conditionally based on the current page context.

Examples

Deactivate a navigation link only on a specific page by combining a body ID with a nav class:

/* Disable the Home nav link only on the homepage (#home body) */
#home nav .home > a {
    pointer-events: none;
    cursor: default;
}

Steps

1. Add a unique ID to the <body> tag on the page where you want the link disabled (e.g., id="home").

2. Ensure the navigation link has a class you can target (e.g., class="home" on the <li> element).

3. Apply the CSS rule above in your stylesheet.

Notes

pointer-events: none is supported in Firefox 3.6+, Safari 3+, and Chrome 5+. It is not supported in older Opera or Internet Explorer versions. CMS platforms like WordPress provide a body_class() function that automatically adds context-specific classes to the body element, making it easy to scope rules like this.

Responsive Navigation Menus with CSS

Responsive menus adapt their presentation or behavior based on the device and screen width. Using CSS media queries you can restyle, relocate, or restructure navigation to provide a better experience on mobile devices without changing the underlying HTML.

Key Approaches

There are three common ways a menu changes across breakpoints:

  • Different styling — fits the available space, may look like an app-style menu.
  • Different content — links adapt to the device context.
  • Different location — navigation may move from a horizontal top bar to a collapsible drawer or footer.

Examples

Collapse a horizontal nav into a vertical stacked list on small screens:

/* Default: horizontal nav */
nav ul {
    display: flex;
    list-style: none;
    margin: 0;
    padding: 0;
}

/* Mobile: vertical stack */
@media (max-width: 600px) {
    nav ul {
        flex-direction: column;
    }
    nav ul li a {
        display: block;
        padding: 12px 16px; /* finger-friendly tap target */
    }
}

Notes

Apple's Human Interface Guidelines recommend tappable targets of at least 44 x 44 points (approximately 57 x 57 px). Luke Wroblewski's Mobile First principle suggests designing for the smallest screen first and progressively enhancing for larger screens. Always test navigation usability on real touch devices, not just by resizing a desktop browser window.

CSS Box Shadow and Text Shadow Examples

CSS provides two shadow properties — box-shadow for elements and text-shadow for text — that let you add depth and visual layering to your designs. The examples below cover common patterns.

Examples

Add a fade/vignette effect at the bottom of an image using a gradient background image on an absolutely-positioned overlay:

.billboard .shadow {
    position: absolute;
    width: 100%;
    height: 142px;
    bottom: 0;
    left: 0;
    margin-bottom: -1px;
    background: url('../img/shadow.png') repeat-x;
}

Simple drop shadow on a box:

.card {
    box-shadow: 0px 4px 8px rgba(0, 0, 0, 0.2);
}

Text shadow for headings:

h1 {
    text-shadow: 2px 2px 4px rgba(0, 0, 0, 0.4);
}

Notes

The box-shadow shorthand is: offset-x offset-y blur-radius spread-radius color. Multiple shadows can be stacked by separating them with commas. For the image overlay pattern, the parent element must have position: relative so the absolutely-positioned shadow layer stays within bounds.

Remove CSS Styling from an Element

Use the CSS :not() pseudo-class to apply styles to all elements except those with a specific class. This lets you opt individual elements out of shared styles without writing separate override rules.

Examples

Style all buttons except those with the class nostyle:

button:not(.nostyle) {
    width: 100px;
    height: 45px;
    background-color: #12aeef;
    border: none;
    box-shadow: 0px 5px 3px #888888;
}

Corresponding HTML — Btn3 will receive no styling:

<button>Btn1</button>
<button>Btn2</button>
<button class="nostyle">Btn3</button>
<button>Btn4</button>
<button>Btn5</button>

Steps

1. Add the class nostyle (or any class name you choose) to elements that should be excluded.

2. Use element:not(.classname) in your CSS selector to target all other instances.

Notes

The :not() pseudo-class accepts a simple selector as its argument. It is well-supported in all modern browsers. To reset all inherited styles on a single element, you can also use all: revert or all: unset on that element directly.

Use Custom Fonts in a Website with @font-face

The CSS @font-face rule lets you load and use custom typefaces by pointing to font files hosted on your server. This avoids relying on system fonts and gives you full control over typography.

Steps

1. Create a fonts/ directory in your project (e.g., under a WordPress plugin or theme folder) and set appropriate read permissions.

2. Convert your .ttf font file into all required web formats (EOT, WOFF, WOFF2, SVG) using a tool such as transfonter.org. The tool also generates the CSS snippet for you.

3. Update the font file paths in the generated CSS and add the @font-face declarations to your stylesheet.

4. Reference the font by its declared font-family name anywhere in your CSS.

Examples

@font-face {
    font-family: 'Bebas Neue Bold';
    src: url('/wp-content/plugins/fonts/BebasNeueBold.eot');
    src: url('/wp-content/plugins/fonts/BebasNeueBold.eot?#iefix') format('embedded-opentype'),
         url('/wp-content/plugins/fonts/BebasNeueBold.woff') format('woff'),
         url('/wp-content/plugins/fonts/BebasNeueBold.ttf') format('truetype'),
         url('/wp-content/plugins/fonts/BebasNeueBold.svg#BebasNeueBold') format('svg');
    font-weight: bold;
    font-style: normal;
}

@font-face {
    font-family: 'Bebas Neue Regular';
    src: url('/wp-content/plugins/fonts/BebasNeueRegular.eot');
    src: url('/wp-content/plugins/fonts/BebasNeueRegular.eot?#iefix') format('embedded-opentype'),
         url('/wp-content/plugins/fonts/BebasNeueRegular.woff') format('woff'),
         url('/wp-content/plugins/fonts/BebasNeueRegular.ttf') format('truetype'),
         url('/wp-content/plugins/fonts/BebasNeueRegular.svg#BebasNeueRegular') format('svg');
    font-weight: normal;
    font-style: normal;
}

/* Using the custom fonts */
.bigh1 {
    font-family: 'Bebas Neue Regular';
    font-size: 7em;
    color: white;
}

#mainheading {
    font-family: 'Bebas Neue Bold';
    font-size: 5em;
    color: black;
}

Notes

The multiple src values provide fallbacks for different browsers. Modern browsers only need WOFF and WOFF2. The EOT format is for legacy Internet Explorer. Always self-host fonts for performance — avoid loading them over slow external CDNs when you can serve them from your own server.

CSS Relative and Absolute Positioning

CSS positioning lets you place elements precisely on the page. position: relative moves an element relative to where it would normally appear in the document flow, while position: absolute removes the element from flow and positions it relative to its nearest positioned ancestor.

Examples

A common pattern is a calendar badge where the month label is absolutely positioned inside a relatively-positioned container:

/* Parent container: relatively positioned */
.calendar {
    background: linear-gradient(to bottom, #fc8200 0%, #9c4e00 100%);
    width: 75px;
    height: 75px;
    line-height: 40px;   /* positions the large day number vertically */
    font-size: 50px;
    color: white;
    text-align: center;
    padding-top: 5px;
    position: relative;
    left: 195px;
}

/* Child element: absolutely positioned within .calendar */
.smallfont {
    font-size: 14px;
    position: absolute;
    top: 40px;
    left: 5px;
}

Steps

1. Set position: relative on the parent element. This creates a positioning context for its children.

2. Set position: absolute on the child element and use top, right, bottom, and left to place it exactly where you want it within the parent.

Notes

An absolutely-positioned element looks for its nearest ancestor with a position value other than static. If no such ancestor exists, it positions itself relative to the initial containing block (the viewport). Always set position: relative on the intended parent to avoid unexpected positioning.

Style Table Rows with CSS

By default, <tr> and <td> elements use their built-in table display roles. In some layouts — especially when building responsive tables — you may need to override these display values using CSS.

Examples

Force a <tr> to behave like a block-level table and each <td> to behave like a full row:

tr {
    display: table;
    width: 100%;
}

td {
    display: table-row;
    background: #efefef;
}

Notes

This technique is useful when reformatting a data table for narrow screens. Each cell stacks vertically, mimicking a definition-list layout. For a full responsive table approach, combine this with a @media query so the standard table layout is preserved on wider screens and only overridden on mobile.

CSS Positioning In Depth

CSS offers several positioning schemes — static, relative, absolute, fixed, and sticky — each suited to different layout requirements. Understanding how these interact, especially with floats and stacking contexts, gives you precise control over page layout.

Containing Floats

When child elements are floated, the parent container collapses because floated elements are removed from the normal document flow. To contain floats, use a clearfix:

/* Clearfix: forces the parent to expand around floated children */
.group::after {
    content: "";
    display: table;
    clear: both;
}

Apply the group class to any container that holds floated children.

The Position Property

/* Static (default) — no offset properties apply */
.box { position: static; }

/* Relative — offset from normal position; still occupies original space */
.box { position: relative; top: 10px; left: 20px; }

/* Absolute — removed from flow; positioned relative to nearest positioned ancestor */
.box { position: absolute; top: 0; right: 0; }

/* Fixed — positioned relative to the viewport; stays in place on scroll */
.box { position: fixed; bottom: 20px; right: 20px; }

/* Sticky — relative until scroll threshold, then fixed */
.box { position: sticky; top: 0; }

Z-Index and Stacking Order

When positioned elements overlap, z-index controls which appears on top. Only elements with a position value other than static respect z-index:

.overlay {
    position: absolute;
    z-index: 100;
}

.content {
    position: relative;
    z-index: 1;
}

Notes

A new stacking context is created by elements with position + z-index, opacity less than 1, or certain CSS transforms. Elements within a stacking context are ordered independently from those outside it. Use browser DevTools to inspect stacking contexts when debugging overlapping elements.

Create a Seven-Column Layout in CSS

Building a seven-column layout requires subdividing a 12-column grid so that all columns fit within the available space. The example below uses WPBakery Page Builder (Visual Composer), but the underlying fraction math applies to any 12-column grid system.

Steps

1. In WPBakery Page Builder, select the row and choose Custom for the column layout.

2. Enter the following column fractions to create a seven-column layout with narrower outer columns and equal inner columns:

1/12 + 2/12 + 2/12 + 2/12 + 2/12 + 2/12 + 1/12

This divides the 12-unit grid into 7 columns: two 1-unit edge columns and five 2-unit inner columns.

Examples

Equivalent CSS using flexbox:

.seven-col-row {
    display: flex;
    gap: 0;
}

.col-1-12 { flex: 1; }   /* 1/12 */
.col-2-12 { flex: 2; }   /* 2/12 */

Notes

Odd column counts (5, 7, 9) do not divide evenly into a 12-column grid, so fractions must add up to exactly 12/12. Double-check your fractions sum to 1 before applying the layout.

Add a Separator Between Menu Items with CSS

Use the CSS ::after pseudo-element with the :not(:last-child) pseudo-class to automatically insert a separator character between navigation items — no extra HTML markup needed.

Examples

Insert a right-facing double angle quotation mark (») between all nav items except the last:

nav ul li:not(:last-child)::after {
    content: '\00BB';       /* Unicode for » */
    position: relative;
    top: -2px;
    padding-right: 8px;
    color: #fff;
}

Steps

1. Target the list items in your nav with nav ul li.

2. Add :not(:last-child) so the separator is not added after the final item.

3. Use ::after to insert the separator as generated content via the content property.

4. Adjust padding-right and color to match your design.

Notes

You can use any Unicode character as the separator: \007C (|), \2022 (•), or \2014 (—) are common choices. This approach works without JavaScript and keeps the HTML clean.

Add a Symbol or Icon to a Button with CSS

You can add a small icon or arrow symbol to a button using CSS background-image without modifying the HTML. This is useful for adding directional indicators (arrows, chevrons) to call-to-action buttons.

Examples

Add an arrow icon to the WooCommerce checkout button using a background image:

a.checkout-button.button.alt.wc-forward {
    background-repeat: no-repeat;
    background-position: 90% center;  /* right-aligned, vertically centered */
    background-size: 6px 9px;
    background-image: url('/images/button-arrow.png');
    border-radius: 8px;
    padding-right: 24px;  /* make room for the icon */
}

Steps

1. Prepare a small icon image (PNG or SVG) for the symbol.

2. Apply background-image to the button element.

3. Use background-position to place the icon (e.g., right-aligned with 90% center).

4. Set background-size to control the icon dimensions.

5. Add padding on the side where the icon appears so the button text does not overlap it.

Notes

For scalable icons, use an inline SVG as a data: URI in the background-image value. For modern icon systems, CSS ::before or ::after pseudo-elements with icon fonts (Font Awesome, etc.) or inline SVG are often a better approach than raster PNG images.

Create Circular Images with CSS

The CSS border-radius property can turn any square element into a circle. Rectangular images require a wrapper element to crop them into a square first before the circular shape is applied.

Examples

Square images — one line of CSS:

.circular--square {
    border-radius: 50%;
}

Landscape images — wrap in a square container with overflow: hidden:

/* HTML */
<div class="circular--landscape">
    <img src="photo.jpg" alt="...">
</div>

/* CSS */
.circular--landscape {
    display: inline-block;
    position: relative;
    width: 200px;
    height: 200px;
    overflow: hidden;
    border-radius: 50%;
}

.circular--landscape img {
    width: auto;
    height: 100%;
    margin-left: -50px;  /* centers the image horizontally */
}

Portrait images — adjust margin-top instead of margin-left:

.circular--portrait {
    display: inline-block;
    position: relative;
    width: 200px;
    height: 200px;
    overflow: hidden;
    border-radius: 50%;
}

.circular--portrait img {
    width: 100%;
    height: auto;
    margin-top: -50px;  /* centers the image vertically */
}

Steps

1. For square images, apply border-radius: 50% directly to the <img> element.

2. For rectangular images, wrap the <img> in a <div> with equal width and height, set overflow: hidden and border-radius: 50% on the wrapper.

3. Adjust the margin-left (landscape) or margin-top (portrait) on the <img> to center the subject within the circle.

Notes

The offset formula is: nudge = 25% of the wrapper size. For a 200 px wrapper that equals 50 px. Use a negative margin to shift the image in the direction that centers the subject. Object-fit is a modern alternative: setting object-fit: cover on the <img> itself (with fixed width and height) handles all image orientations without a wrapper element.