Optimizing CSS

Option C: Smart Single File CSS Implementation Plan

Overview

Create one optimized CSS file with page-specific targeting using body classes. This eliminates external dependencies while keeping deployment simple.


Phase 1: Preparation & Backup

Step 1: Document Current Setup

# Create analysis folder
mkdir css-optimization
cd css-optimization

# Document current external CSS links
echo "=== Current CSS Links ===" > current-setup.txt
for page in *.php; do
  echo "--- $page ---" >> current-setup.txt
  grep -n "stylesheet\|@import\|fonts.googleapis" "$page" >> current-setup.txt
  echo "" >> current-setup.txt
done

Step 2: Identify Your Pages & Custom Classes

Create page-inventory.txt:

index.php     - Homepage (hero section, weather widget)
about.php     - About page (team grid, contact info)
gallery.php   - Photo gallery (grid layout, lightbox)
contact.php   - Contact form (form styling, map)
blog.php      - Blog listing (post cards, pagination)
news.php      - News updates (article layout)

Step 3: Create Backup

cp -r your-website-folder your-website-backup-$(date +%Y%m%d)

Phase 2: Download & Organize Assets

Step 1: Download W3.CSS

# Create CSS directory structure
mkdir -p css/fonts css/build

# Download W3.CSS
curl -o css/build/w3-original.css https://www.w3schools.com/w3css/4/w3.css

Step 2: Download Google Fonts

  1. Visit https://gwfh.mranftl.com/fonts
  2. Find your fonts (check your current <link> tags)
  3. Select weights you use (usually 400, 700)
  4. Choose “Modern Browsers”
  5. Copy CSS and download font files

Save as css/fonts.css:

/* Example - replace with your actual fonts */
@font-face {
  font-family: 'Open Sans';
  font-style: normal;
  font-weight: 400;
  src: url('fonts/open-sans-400.woff2') format('woff2');
  font-display: swap;
}

@font-face {
  font-family: 'Open Sans';
  font-style: normal;
  font-weight: 700;
  src: url('fonts/open-sans-700.woff2') format('woff2');
  font-display: swap;
}

Step 3: Extract Your Custom CSS

Copy your existing custom CSS to css/build/custom-original.css


Phase 3: Implement Body Classes

Step 1: Add Body Classes to Each Page

Update each PHP page’s <body> tag:

<!-- index.php -->
<body class="page-index">

<!-- about.php -->
<body class="page-about">

<!-- gallery.php -->
<body class="page-gallery">

<!-- contact.php -->
<body class="page-contact">

<!-- blog.php -->
<body class="page-blog">

<!-- news.php -->
<body class="page-news">

Step 2: Test Body Classes Work

Add temporary CSS to verify:

<style>
body.page-index { background: lightblue; }
body.page-about { background: lightgreen; }
/* etc... */
</style>

Visit each page to confirm different background colors appear.


Phase 4: Analyze & Purge CSS

Step 1: Install Analysis Tools

# Install PurgeCSS and CSS minifier
npm install -g purgecss csso-cli

Step 2: Create PurgeCSS Configuration

Save as purgecss.config.js:

module.exports = {
  content: [
    '*.php',
    '**/*.php',
    '*.html',
    '**/*.html'
  ],
  css: ['css/build/w3-original.css'],
  safelist: [
    // Interactive classes (JavaScript)
    'w3-show', 'w3-hide',
    'w3-animate-opacity', 'w3-animate-left', 'w3-animate-right',
    'w3-animate-top', 'w3-animate-bottom', 'w3-animate-zoom',
    
    // Modal and overlay classes
    'w3-modal', 'w3-overlay',
    
    // State classes
    'active', 'selected', 'current', 'open', 'closed',
    
    // Dynamic classes (regex patterns)
    /^w3-animate-/,
    /^page-/,
    
    // Add your custom interactive classes here
    'mobile-menu-open',
    'gallery-active',
    // etc...
  ],
  defaultExtractor: content => content.match(/[\w-/:]+(?<!:)/g) || []
}

Step 3: Run CSS Analysis

# Purge W3.CSS
purgecss --config purgecss.config.js --output css/build/

# This creates css/build/w3-original.css (purged version)
mv css/build/w3-original.css css/build/w3-purged.css

Phase 5: Create Smart Single File

Step 1: Reorganize Custom CSS with Body Class Targeting

Create css/build/custom-targeted.css:

/* ================================================
   SHARED STYLES (Used across multiple pages)
   ================================================ */

/* Custom header/footer - used on all pages */
.custom-header {
  background: #333;
  color: white;
  padding: 1rem 0;
}

.custom-footer {
  background: #f5f5f5;
  text-align: center;
  padding: 2rem 0;
}

/* Custom navigation - used on all pages */
.custom-nav {
  /* your nav styles */
}

/* ================================================
   PAGE-SPECIFIC STYLES
   ================================================ */

/* ===== INDEX PAGE STYLES ===== */
body.page-index .hero-banner {
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  color: white;
  padding: 4rem 0;
  text-align: center;
}

body.page-index .weather-widget {
  background: rgba(255,255,255,0.9);
  border-radius: 8px;
  padding: 1rem;
  margin: 2rem 0;
}

/* ===== ABOUT PAGE STYLES ===== */
body.page-about .team-grid {
  display: grid;
  grid-template-columns: repeat(auto-fit, minmax(250px, 1fr));
  gap: 2rem;
  margin: 2rem 0;
}

body.page-about .team-member {
  text-align: center;
  padding: 1rem;
  border: 1px solid #ddd;
  border-radius: 8px;
}

/* ===== GALLERY PAGE STYLES ===== */
body.page-gallery .gallery-grid {
  display: grid;
  grid-template-columns: repeat(auto-fit, minmax(200px, 1fr));
  gap: 1rem;
  padding: 2rem 0;
}

body.page-gallery .gallery-item {
  aspect-ratio: 1;
  overflow: hidden;
  border-radius: 4px;
  cursor: pointer;
  transition: transform 0.3s ease;
}

body.page-gallery .gallery-item:hover {
  transform: scale(1.05);
}

/* ===== CONTACT PAGE STYLES ===== */
body.page-contact .contact-form {
  max-width: 600px;
  margin: 0 auto;
  padding: 2rem;
  background: #f9f9f9;
  border-radius: 8px;
}

body.page-contact .form-group {
  margin-bottom: 1.5rem;
}

/* ===== BLOG PAGE STYLES ===== */
body.page-blog .post-grid {
  display: grid;
  grid-template-columns: repeat(auto-fit, minmax(300px, 1fr));
  gap: 2rem;
  margin: 2rem 0;
}

body.page-blog .post-card {
  border: 1px solid #ddd;
  border-radius: 8px;
  overflow: hidden;
  transition: box-shadow 0.3s ease;
}

body.page-blog .post-card:hover {
  box-shadow: 0 4px 12px rgba(0,0,0,0.1);
}

/* ===== NEWS PAGE STYLES ===== */
body.page-news .news-article {
  border-bottom: 1px solid #eee;
  padding: 2rem 0;
}

body.page-news .news-article:last-child {
  border-bottom: none;
}

/* ================================================
   RESPONSIVE STYLES
   ================================================ */

@media (max-width: 768px) {
  /* Mobile adjustments for specific pages */
  body.page-index .hero-banner {
    padding: 2rem 0;
  }
  
  body.page-gallery .gallery-grid {
    grid-template-columns: repeat(2, 1fr);
  }
  
  body.page-contact .contact-form {
    margin: 0 1rem;
  }
}

Step 2: Combine All CSS Files

Create build script build-css.sh:

#!/bin/bash
echo "Building optimized CSS file..."

# Combine all CSS in the correct order
cat > css/main.css << 'EOF'
/*! 
 * Optimized CSS for Scootercam.net
 * Generated: $(date)
 * Contains: Fonts + W3.CSS (purged) + Custom Styles
 */

EOF

# Add fonts
echo "/* ===== FONTS ===== */" >> css/main.css
cat css/fonts.css >> css/main.css

echo "" >> css/main.css
echo "/* ===== W3.CSS (PURGED) ===== */" >> css/main.css
cat css/build/w3-purged.css >> css/main.css

echo "" >> css/main.css
echo "/* ===== CUSTOM STYLES ===== */" >> css/main.css
cat css/build/custom-targeted.css >> css/main.css

echo "CSS combination complete!"
echo "Size: $(wc -c < css/main.css) bytes"

Step 3: Minify the Final CSS

# Make script executable and run
chmod +x build-css.sh
./build-css.sh

# Minify the combined CSS
csso css/main.css --output css/main.min.css

echo "Final minified size: $(wc -c < css/main.min.css) bytes"

Phase 6: Update All Pages

Step 1: Remove Old CSS Links

Remove these from all pages:

<!-- Remove these lines -->
<link rel="stylesheet" href="https://www.w3schools.com/w3css/4/w3.css">
<link href="https://fonts.googleapis.com/css2?family=..." rel="stylesheet">
<link rel="stylesheet" href="custom.css">

Step 2: Add New CSS Link

Add to the <head> of every page:

<!-- Optimized CSS -->
<link rel="preload" href="css/main.min.css" as="style">
<link rel="stylesheet" href="css/main.min.css">

Step 3: Add Performance Hints (Optional)

<!-- Add these for better performance -->
<link rel="preload" href="css/fonts/your-font-400.woff2" as="font" type="font/woff2" crossorigin>
<link rel="dns-prefetch" href="//your-domain.com">

Phase 7: Testing & Validation

Step 1: Visual Testing Checklist

Create testing-checklist.md:

## Visual Testing Checklist

### All Pages:
- [ ] Header displays correctly
- [ ] Navigation works
- [ ] Footer appears properly
- [ ] Fonts load correctly
- [ ] No broken styling

### Page-Specific Testing:
- [ ] index.php: Hero banner, weather widget
- [ ] about.php: Team grid, contact info  
- [ ] gallery.php: Photo grid, hover effects
- [ ] contact.php: Form styling, layout
- [ ] blog.php: Post cards, grid layout
- [ ] news.php: Article styling

### Responsive Testing:
- [ ] Mobile view (320px-768px)
- [ ] Tablet view (768px-1024px) 
- [ ] Desktop view (1024px+)

### Interactive Testing:
- [ ] Buttons work and style correctly
- [ ] Form interactions
- [ ] Any JavaScript-toggled classes
- [ ] Hover effects

Step 2: Performance Testing

Create test-performance.sh:

#!/bin/bash
echo "=== Performance Testing ==="

echo "CSS file size:"
ls -lh css/main.min.css

echo ""
echo "Testing page load times..."
for page in index about gallery contact blog news; do
  echo "Testing ${page}.php..."
  curl -w "Time: %{time_total}s, Size: %{size_download} bytes\n" \
       -o /dev/null -s "http://localhost/${page}.php"
done

echo ""
echo "Testing external requests (should be 0 for CSS/fonts):"
curl -s "http://localhost/index.php" | grep -E "(fonts\.googleapis|w3schools)" || echo "✓ No external CSS/font requests found"

Step 3: Validation

# CSS Validation
echo "Validating CSS..."
curl -s -F "file=@css/main.min.css" -F "output=text" \
  "https://jigsaw.w3.org/css-validator/validator" | grep -E "(Valid|Error|Warning)"

# HTML Validation (check that body classes don't break anything)
for page in *.php; do
  echo "Checking $page for valid HTML..."
  # Use local validation or online service
done

Phase 8: Deployment & Monitoring

Step 1: Deploy Files

# Upload to your server
scp -r css/ user@yourserver.com:/path/to/website/
scp *.php user@yourserver.com:/path/to/website/

# Or use FTP/cPanel file manager to upload:
# - css/main.min.css
# - css/fonts/ (entire folder)
# - Updated *.php files

Step 2: Configure Server (Optional)

Add to .htaccess for better caching:

# Cache CSS and fonts for 1 year
<filesMatch "\.(css|woff2|woff)$">
    ExpiresActive on
    ExpiresDefault "access plus 1 year"
</filesMatch>

# Enable gzip compression
<IfModule mod_deflate.c>
    AddOutputFilterByType DEFLATE text/css
    AddOutputFilterByType DEFLATE font/woff2
</IfModule>

Step 3: Monitor Results

Create monitor.sh:

#!/bin/bash
echo "=== Site Monitoring ==="

echo "Checking external requests:"
curl -s "https://yoursite.com" | grep -c "fonts.googleapis\|w3schools" || echo "✓ No external CSS requests"

echo ""
echo "CSS file size on server:"
curl -s -I "https://yoursite.com/css/main.min.css" | grep -i content-length

echo ""
echo "Page speed test:"
curl -w "Total time: %{time_total}s\n" -o /dev/null -s "https://yoursite.com"

Expected Results

File Size Comparison

BEFORE:
- W3.CSS: ~87KB
- Google Fonts: ~15-30KB
- Your custom CSS: ~5-15KB  
- Total: ~110-135KB + external requests

AFTER:
- main.min.css: ~25-40KB (75% reduction)
- All fonts local: 0 external requests
- Total: ~25-40KB, fully cached

Performance Improvements

  • External Requests: 2-3 → 0
  • CSS Load Time: 800ms+ → 200-400ms
  • First Paint: Faster by 300-500ms
  • Caching: Full control, 1-year cache possible

Maintenance Benefits

  • Single CSS file to manage
  • Easy to add new page-specific styles
  • Simple deployment process
  • No external dependencies to break

Troubleshooting

Common Issues & Solutions

Styles Missing After Update:

# Check if class exists in original
grep "your-missing-class" css/build/custom-original.css

# Check if it was purged
grep "your-missing-class" css/build/w3-purged.css

# Add to safelist if needed

Page-Specific Styles Not Working:

# Verify body class exists
curl -s "http://localhost/page.php" | grep -o 'body class="[^"]*"'

# Check CSS syntax
grep -A 5 "body.page-name" css/main.css

Fonts Not Loading:

# Check font file paths
ls -la css/fonts/

# Test font file access
curl -I "http://localhost/css/fonts/your-font.woff2"

# Verify CSS font-face syntax
grep -A 10 "@font-face" css/main.css

CSS Too Large:

# Rerun PurgeCSS with more aggressive settings
# Check for duplicate styles
# Remove unused responsive breakpoints

This plan will give you a highly optimized, self-contained CSS setup that’s simple to maintain and deploy!

Leave a Comment