Fading Coder

One Final Commit for the Last Sprint

Home > Tech > Content

Essential CSS Techniques for Beginner Frontend Developers

Tech 1

CSS Sprites (Sprite Sheets)

Why Use CSS Sprites?

When a page includes many small decorative background images, the server has to handle dozens of separate image requests, which increases server load and slows down page rendering significantly. CSS sprite technology solves this problem by combining all small background images into a single large image, so the server only needs one request to deliver all icons, cutting overhead and improving load speed.

Core principle: Only display the desired portion of the combined image via CSS background positioning.

How to Use CSS Sprites

Key implementation rules:

  1. Sprites are designed for background images, with multiple small icons merged into one large sheet
  2. The combined image is called a sprite sheet
  3. Adjust the visible icon by changing the background-position property
  4. Offset values match the X and Y coordinates of the target icon; note browser coordinate systems differ from standard Cartesian systems
  5. Most of the time you shift the background up and left, so offset values are negative
  6. You must accurately measure the size and position of each small icon in the sheet before implementation

Summary:

  • Sprites are for small background icons
  • The effect relies entirely on background-position to shift the image
  • Offsets are almost always negative; remember: X increases right, decreases left, Y increases down, decreases up.

Icon Fonts

Origin of Icon Fonts

Icon fonts are built for common generic small icons across web pages. While sprites work well, they have clear drawbacks:

  • The total image file size is still relatively large
  • Icons get blurry when scaled
  • It is very hard to modify icons after the sprite sheet is finished

Icon fonts (iconfont) solve all these issues: they render as icons, but behave like standard text fonts.

Benefits of Icon Fonts

  1. Lightweight: A single icon font file is much smaller than a collection of icon images, renders immediately after loading, and reduces server requests
  2. Flexible: Since they are text-based, you can easily change color, add drop shadows, adjust transparency, rotate, or apply any other CSS text effect
  3. Compatibility: Icon fonts work on almost all modern and older browsers, so you can use them without major issues

Important note: Icon fonts do not replace CSS sprites, they just improve and optimize icon workflows.

  • Use icon fonts for simple small icons
  • Use CSS sprites for more complex, detailed small graphics

Standard workflow for icon fonts:

  1. Download icon font files from public repositories
  2. Import font files into your HTML project
  3. Add new icons to your set later as needed

CSS Triangles

You can create common triangle shapes directly with CSS, no need for image files or icon fonts. Triangles are built using CSS border behavior, as shown below:

.triangle {
    width: 0; 
    height: 0;
    border: 50px solid transparent;
	border-color: red green blue black;
	line-height: 0;
    font-size: 0;
}

Key notes:

  • Borders are used to simulate the triangle shape
  • The container must have width and height set to 0
  • Define all four borders, set unused borders to transparent, only keep the desired border's color
  • Add font-size: 0; line-height: 0; to fix rendering bugs in older browsers

CSS User Interface Styles

UI styles adjust interaction behavior to improve user experience:

Mouse Cursor Style (cursor)

Change the mouse pointer shape when hovering over an element:

.clickable-item {
    cursor: pointer;
}

This property accepts many predefined values for different use cases.

Outline (outline)

Remove the default blue focus outline from form inputs with this rule:

input {
    outline: none;
}

Disable Textarea Resizing (resize)

In most productino projects, you don't want users to drag and resize textarea elements:

textarea {
  	resize: none;
}

vertical-align Property Usage

Definition

The vertical-align CSS property is commonly used to vertically align images, form elements, and other inline-block elements with adjacent text. It only works on inline and inline-block elements, and controls their vertical alignment relative to parent content.

Available values:

vertical-align : baseline | top | middle | bottom 

Aligning Images/Forms with Text

Images and form elements are inline-block by default, and use baseline alignment as the default setting. Set vertical-align: middle on these elements to get perfect vertical centering with adjacent text.

Fixing Default Bottom Gap Under Images

A common bug: a small empty gap appears below inline images. This is caused by default baseline alignment of inline-block elements. There are two common fixes:

  1. Add vertical-align: middle (or top/bottom) to the image (this is the recommended approach)
  2. Convert the image to a block-level element with display: block

Truncating Overflow Text with Ellipsis

Single Line Text Truncation

Truncating single line overflow text to an ellipsis requires three mandatory CSS rules:

/* Force text to display on one line */
white-space: nowrap;
/* Hide content that exceeds container bounds */
overflow: hidden;
/* Replace overflow content with an ellipsis */
text-overflow: ellipsis;

Multi Line Text Truncation

Multi line truncation has limited compatibility, and works best on WebKit-based browsers (most mobile browsers use the WebKit kernel):

/* Hide overflow content */
overflow: hidden;
/* Replace overflow with an ellipsis */
text-overflow: ellipsis;
/* Enable flexible box layout */
display: -webkit-box;
/* Set maximum number of visible lines */
-webkit-line-clamp: 2;
/* Arrange child elements vertically */
-webkit-box-orient: vertical;

For production projects, it is often easier for backend developers to truncate text to the desired length directly.

Common CSS Layout Tricks

Using Negative margin Values

Negative margins have two common useful applications:

  1. For multiple adjacent boxes with borders, set a negative 1px left margin on each box to overlap adjacent borders, avoidign unsightly double-thick borders
  2. When hovering over a box, increase the element's stacking order: add position: relative if the element has no existing positioning, then adjust z-index to bring the hovered box to the front

Wrapping Text Around Floated Elements

Leverage native float behavior: floated elements do not block text flow, so text automatically wraps around the float. This is perfect for common layouts like images inserted into article content.

Inline-Block for Centered Pagination

For pagination that needs to be centered horizontally: convert all pagination link elements to inline-block, then set text-align: center on the parent container. This automatically centers the entire pagination block perfectly, leveraging the natural behavior of inline-block elements.

CSS Practical Project

Example: Flash Sale Price Tag

This example demonstrates practical use of CSS triangles:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <title>CSS Triangle Practical Example</title>
    <style>
        .flash-sale-price {
            width: 160px;
            height: 24px;
            line-height: 24px;
            border: 1px solid red;
            margin: 0 auto;
        }
        .flash-badge {
            position: relative;
            float: left;
            width: 90px;
            height: 100%;
            background-color: red;
            text-align: center;
            color: #fff;
            font-weight: 700;
            margin-right: 8px;
        }
        .flash-badge i {
            position: absolute;
            right: 0;
            top: 0;
            width: 0;
            height: 0;
            border-color: transparent #fff transparent transparent;
            border-style: solid;
            border-width: 24px 10px 0 0;
        }
        .original-price {
            font-size: 12px;
            color: gray;
            text-decoration: line-through;
        }
    </style>
</head>
<body>
    <div class="flash-sale-price">
        <span class="flash-badge">
            ¥1650
            <i></i>
        </span>
        <span class="original-price">¥5650</span>
    </div>
</body>
</html>

Related Articles

Understanding Strong and Weak References in Java

Strong References Strong reference are the most prevalent type of object referencing in Java. When an object has a strong reference pointing to it, the garbage collector will not reclaim its memory. F...

Comprehensive Guide to SSTI Explained with Payload Bypass Techniques

Introduction Server-Side Template Injection (SSTI) is a vulnerability in web applications where user input is improper handled within the template engine and executed on the server. This exploit can r...

Implement Image Upload Functionality for Django Integrated TinyMCE Editor

Django’s Admin panel is highly user-friendly, and pairing it with TinyMCE, an effective rich text editor, simplifies content management significantly. Combining the two is particular useful for bloggi...

Leave a Comment

Anonymous

◎Feel free to join the discussion and share your thoughts.