Article Archives

Accidental CSS Resets

Any time you use a shorthand property in CSS, you set all the values for all the properties it deals with. It's not a bug, it's just how CSS works. I've seen it confuse people plenty of times. Let's shine a light on the issue to hopefully make it more understood.

(more…)

Thoughts on the Advertising Ecosystem

There are lots of business on the web. One type of those is a website that sells products or services. Those websites employ people who work on the site, incur server costs, material costs, etc. The products and services they provide are useful to people, and they pay for them. Business. Cool.

Those websites need customers. They need people to come to those sites. There are all sorts of ways to do that. Word of mouth. SEO. Wear a costume and wave a sign at traffic. Some more effective than others. The most effective, generally is to do marketing and, as a subset of that, do advertising. Web advertising, in particular, as potential customers are just a click away.

Where do you do that advertising? Enter another type of business on the web: the publication.

(more…)

CSS-Tricks Chronicle XXI

As I write I'm half way through my month-long stay at Hilton Head Health. I like coming here to keep my weight in check. I hope to break some personal records while I'm here this time. It's also been a good way to escape some of the Wisconsin winter. It has been mild up until I left, but it sounds like February has been pretty rough so far.

(more…)

Sponsor: Stack

Stack is what we use here at Team CSS-Tricks to keep organized. Check out our interview over on their site.

There is a lot to keep track of: article ideas, site bugs, site improvement ideas, guest posts, etc. Also business things like invoicing statuses, accounting tasks, and merchandise. Stack allows us to break all those things up into projects. Then each project has tasks, like "Update the Sprites article" or "Order more green T-Shirts" - which get organized by custom status like "to do", "doing", and "done". Each task has notes, checklists, and discussion specific to that task.

The team can be a part of (and get notifications for) whatever projects and tasks are relevant to them. I really like Stack, because it matches how I think about organization. Ongoing projects, tasks-with-statuses, and in-task notes. It's that three-level system that makes so much sense. It gives you a framework, so it's not too loose in that regard, but it also doesn't limit how you want to organize. If I was going to build organizational software, it would probably be just like this. Good thing I don't have to!

FLIP Your Animations

First, Last, Invert, Play.

Paul Lewis demonstrates a performant way to approach animations. It's the opposite of how you normally think of them. In this approach, the state you first see elements in is the the result of manipulation from the elements final state. Then you remove all the transforms (et al.) to trigger the animation.

BrowserSync 2.0

It was only a year and a half ago when Shane Osborne introduced BrowserSync here. It does those things we really love as front end devs: style injection, reloading when necessary, and running a server so you can test across multiple devices and see that stuff happen across all of them. But it did more: synced forms as-you-type, synced scroll position across devices, even followed links so as you navigated around the site all the devices would come with you.

It's great to see 2.0 launch with a UI for configuring it and some nice new features.

Styled Range Sliders

Ana Tudor produced dozens of beautiful examples, all with just a single <input type="range">. We've covered the how-to before, but Ana goes deeper adding useful functionality and using new uncharted stuff like /deep/.

Responsible Social Share Links

Using actual social sharing buttons, as provided by Twitter or Facebook (et al.) is a no-go for most performance-concerned or privacy-concerned websites. Too slow, too dangerous. It's kind of a shame though, as those buttons are nicely functional. An alternative is "share intent" URL's, which generally link to a barebones page in which to share the content. Jonathan Suh shares how you can fancy those up a bit with popup windows. I like it, feels much nicer.

Inline SVG with Grunticon Fallback

Grunticon 2 is out! It's got a cool new website. Grunticon is a damn fine tool for building an SVG icon system. The workflow is like:

  1. Have a folder full of SVG icons
  2. Run Grunticon on that folder, which produces everything you need
  3. Put the bit of JavaScript in the <head>
  4. Use HTML like <div class="icon-image"></div> where you want icons
  5. Icons everywhere!

Grunticon 2 even has a method for injecting inline <svg>, so that you have all those advantages, like scripting, animating, CSS control, etc. You just add an attribute:

<div class="icon-burger alt" data-grunticon-embed></div>

You'd be good using Grunticon just exactly how it is. It just is a bit of a different approach than the one I've been talking about a lot, which uses an SVG sprite and inline <svg><use></use></svg>.

The way I show it, you start with inline <svg> in the document where you want the icons, and handle fallbacks from there. The possible advantages to this are:

  • If inline SVG is supported, no DOM manipulation happens at all, everything is just left alone and works.
  • It's a bit easier to rip out the fallback one day if you decide you no longer need it.
  • (Thanks to Scott pointing out below): Non-JS users would get SVG icons instead of fallback PNG if you chose not to Ajax for the sprite and just embed it in the document.

What's cool about inline-<svg>-first is that we can still use Grunticon to help us with the fallbacks!

1. Get a folder full of SVGs + Make SVG sprite

You can get them in any possible way you get get/create SVG. We'll use IcoMoon here because it's easy and awesome and gives us the SVG sprite right off the bat. If you want to make sprite creation part of your build, read up.

2. Use the icons as normal in your document

Simple example:

<button>
  <svg xmlns="http://www.w3.org/2000/svg" class="icon icon-home">
    <use xlink:href="#icon-home"></use>
  </svg>
  Go Home
</button>

Make sure to use the xmlns="http://www.w3.org/2000/svg" on them, which is required to give them layout in IE 8.

3. Use the normal Grunticon build

In the Gruntfile.js:

grunticon: {
  icons: {
    files: [{
      expand: true,
      cwd: "svg/",
      src: ["*.svg"],
      dest: "fallbacks/"
    }]
    // We don't need the enhanceSVG option here
  }
}

This produces all the PNG fallback stuff for you.

4. In the head of the document, run an inline SVG test

Modernizr has a great inline SVG test we'll hijack.

var supportsSvg = function() {
  var div = document.createElement('div');
  div.innerHTML = '<svg/>';
  return (div.firstChild && div.firstChild.namespaceURI) == 'http://www.w3.org/2000/svg';
};

if (!supportsSvg()) {

  // Do Grunticon stuff

} else {

  // Ajax for SVG sprite

}

5. If the test says inline SVG is supported, Ajax for the sprite

We've covered this before:

var ajax = new XMLHttpRequest();
ajax.open("GET", "svgdefs.svg", true);
ajax.responseType = "document";
ajax.onload = function(e) {
  document.body.insertBefore(ajax.responseXML.documentElement,
                             document.body.childNodes[0]);
}
ajax.send();

This has nothing to do with fallbacks, this is just the normal process of fetching the icons in supported browsers. We do this so it works in IE 9/10/11 and we can browser-cache the sprite.

6. If the test says inline SVG is not supported, use Grunticon

It's just ever-so-slightly modified in that you delete first CSS file in the grunticon() call. That's the one where SVG is supported, and we already have that covered.

// Inline script of grunticon.load.js here
grunticon(["", "/fallbacks/icons.data.png.css", "/fallbacks/icons.fallback.css"]);

Seems to work pretty well

Modern browsers

Still happy in IE 9, falls back in IE 8 and Android well.

If you need IE 6 and 7 too...

As is, we're using the <svg> element itself and setting a background on it as needed for fallbacks. IE 8 can do that, but IE 6 and 7 can't. The SVG element will just disappear (even if you use the HTML5Shiv, weirdly enough).

If you're in the position you need to support these ancient browsers, move the class names up to a wrapping div instead:

<div class="icon icon-credit">
  <svg xmlns="http://www.w3.org/2000/svg" class="icon icon-arrow-right"><use xlink:href="#icon-arrow-right"></use></svg>
</div>

Another notable IE 6-7-8 issue: you don't get background-size, so, generate the PNGs in the exact size you're going to use them.

Repo

I tossed the concept up in a repo in case I screwed stuff up and y'all want to fix it.

Sponsored: Team Communication Starts with HipChat

Give your team the right tools to communicate. HipChat combines IM, group chat rooms, file sharing, screen sharing, video chat and audio calls - into one simple team communication solution.

Don't want to walk to the other side of the office? Relax, your co-workers are just keystrokes away. Big project? Create a group chat room for your team members to collaborate and make decisions. Want to integrate with other tools? We've got over 50 integrations, from the practical like GitHub push notifications, to the fun like Giphy search.

Best of all - get your entire team on HipChat for free. HipChat is free for unlimited users and if you're looking for video chat and screen sharing, its just $2/user per month. Give HipChat a whirl.

Note from Chris: every single person I know that uses HipChat loves it.

Transitioning to SCSS at Scale

I like Dan Na's introduction here:

Naively, CSS appears easy to comprehend — it doesn't have many programming constructs, and it's a declarative syntax that describes the appearance of the DOM rather than an executable language. Ironically it's this lack of functionality that can make CSS difficult to reason about.

I've tried to make the pitch the preprocessing makes CSS easier (not harder) myself.

You can copy() from the console

You can in Blink/WebKit, anyway. You can't directly in JavaScript, as I'm sure that's some security (or good taste) issue that just isn't allowed. Sites that do it tend to rely on Flash. But it works in the console, and that can be all kinds of useful!

(more…)

Simple CSS-Only Row and Column Highlighting

Highlighting rows of a table is pretty darn easy in CSS. tr:hover { background: yellow; } does well there. But highlighting columns has always been a little trickier, because there is no single HTML element that is parent to table cells in a column. A dash of JavaScript can handle it easily, but Andrew Howe recently emailed me to share a little trick he found on StackOverflow, posted by Matt Walton.

It was a few years old, so I thought I'd just clean it up and post it here.

(more…)

Sponsor: Ironhack

Ironhack is a coding school that offers full-time, immersive 8-week courses in Web & iOS development. Founded in Madrid and Barcelona, Ironhack recently launched its third campus in Miami and is accepting applications for its March 16th Web Development cohort.

Receive instruction from experts, hailing from leading technology companies such as Spotify, Yahoo and eBay, among others. In addition to teaching relevant technologies, they impart to you their methodologies for making quality software.

Ironhack provides career support to all its students and alumni through their network of hiring partners.

Note from Chris: I'm a believer. Web worker education is changing and Ironhack is on the front lines. The Miami campus looks awesome and that's great for U.S. folks, but take note European readers, they have the same courses in Spain throughout 2015.

Fun with line-height!

The line-height property in CSS controls the space between lines of text. It is often set in a unitless value (e.g. line-height: 1.4;) so that it is proportional to the font-size. It's a vital property for typographic control. Too low and lines are awkwardly squished together; too high and lines are awkwardly far apart. Both inhibit readability. But you probably already know that.

In this article we'll focus on some trickery. If you know (or can figure out) the exact value of line-height, you can do some neat stuff!

(more…)

“The Escalator”

Patrick Stirling of The Guardian shows off some new ads formats they are using. The first two look like they are just using some @media queries to shuffle things around and resize them. I wasn't able to find a live one to look under the hood at though. It would be really neat to see SVG be used for these because 1) you could make it nicely accessible with real text 2) The scale-and-maintain-proportions ability (even text) would seem appealing. 3) SVG-as-<img> has its own viewport, so contained @media queries work could be based on how wide the ad is, not how wide the screen is.

The third, "The Escalator", is a clever one where the whole ad is revealed only as you scroll. Looks like probably some background-attachment: fixed; action.

I always dig it when companies write about their thinking behind new design. Here's another good example of that from this week.

“Of” vs “On” the Web

Jeremy Keith attempts to make this distinction, using Angular and the concept of "enterprise" software as the catalyst.

"Of the web": Built of fundamental principles of the web. Universal access.

"On the web": The web as a delivery mechanism. The owners dictate use.

Jeremy, who has been banging the progressive enhancement drum since forever, is predictably an "of the web" kinda guy. He only takes issue with the fact that other folks might be forced into working against their principals because of an above-their-head software choice.

I'm slightly less concerned. It actually makes me feel better thinking of things in those terms. While I feel more aligned with the fundamental-principles thinking, I've never held it against any website for dictating how it can be used. There is also gray area here. Every website I've ever worked on had to make choices about what it can feasibly support, because business.

Official Responsive Images Plugin for WordPress

Remember Tim Evko's guest post on responsive images in WordPress? Here's some news on that:

  • It's now the official WordPress plugin of the Responsive Images Community Group (RICG). It's on on GitHub here and in the Plugin Directory.
  • It now uses the more appropriate srcset attribute instead of <picture>, since it just does resolution switching.
  • It's endorsed by the WordPress core team, on track to be a "featured plugin" in the next release, and may ultimately end up in core itself.

Pretty cool!

Web Devvy Ways to Practice Gratitude and Empathy

Have you seen THIS IS WATER? It's great. It's about choosing to think differently, especially when frustrated. I think about it all the time. For instance, every time someone cuts me off on the road, I assume they are rushing someone to the hospital. It doesn't always work, but it's nice when it does. And it's not just a trick, it's learning to think differently.

(more…)

The CSS at…

There was a fun little trend toward the end of last year where companies were posting their approach to CSS. The tools involved, the methodologies, the thinking, and the data and numbers behind it. Mark Otto kicked it off, best I can tell. I mostly just wanted to post a list of them here, since that's perfect fodder for CSS-Tricks. I ended up slapping it into a table with a few bits of data that are easy to compare, just for fun.

(more…)

Abusing CSS3’s nth-child selector to invent new ones

Matt Mastracci on combining existing positional selectors in interesting ways to create logic you might not have thought possible. For instance, select all elements only if there are five of them, with:

span:first-child:nth-last-child(5),
span:first-child:nth-last-child(5) ~ span { 
  /* select the span if its BOTH first and 5th from the end, then all spans after it. */
}

The usefulness lies in applying special layout to accommodate unknown markup.

Reminds me of an old CSS parlor trick I saw Estelle Weyl did where she sized columns perfectly without knowing how many there would be.

Strategies for Keeping CSS Specificity Low

Keeping CSS specificity low across all the selectors in your project is a worthy goal. It's generally a sign that things are in relative harmony. You aren't fighting against yourself and you have plenty of room to override styles when you need to. Specificity on selectors tends to creep up over time, and there is a hard ceiling to that. I'm sure we've all felt the pain of !important tags and inline styles.

So how do we keep that specificity low over time?

(more…)

How to Back Up Your WordPress Database

WordPress stores a ton of important stuff in the database. You probably know your actual content is in the database: blog posts, pages, custom post types, comments, etc.

But the database stores more than content. Much more. Just to name a few:

  • Plugin settings
  • Theme settings
  • Widgets & sidebar content
  • Layouts & templates (if you use a fancy drag-and-drop theme)
  • Cron schedules
  • User accounts
  • Menus

Holy cow - you can't lose that stuff! It doesn't matter if your site is big, small, live or in development - backing up is for every WordPress site.

If you're a WordPress designer or developer, think about how much care you take to save the PHP, HTML, or CSS code you write. You probably use version control. At the very least, you don't rely on a single copy of your code - that'd be risky! So let's take that same care with the much more important database.

WordPress database backups can be taken numerous ways, ranging from "highly-technical" to "supremely easy". How (and how often) you take backups will vary depending on the importance of the site you're working on.

Let's walk through some of the ways you can back up your WordPress database.

How to Back Up With mysqldump

Using the command line for backups is a manual process, and can be a bit daunting if you're not comfortable on the command line. But even if you're afraid of the shell, backing up using mysqldump isn't too awful hard. If you aren't comfortable with it, skip to the next section on using phpMyAdmin for backups.

  • Recommended for: Development & non-critical sites
  • Difficulty: Sorta hard
  • Cost: Free

mysqldump is an appropriately-named program for dumping a MySQL database. No surprises here.

With default settings, mysqldump will generate a .sql file, which is just a list of SQL commands - CREATE TABLEs, INSERTs, etc.

If you were to run each of the SQL commands in the .sql file generated by mysqldump, you'd end up with an exact copy of your WordPress database - which is what we're trying to get!

To run mysqldump, you'll need to access the command line for your server.

ssh user@your-website.com

Some software can help you connect to your server through SSH. Here's the setup screen for that in Coda:

To run mysqldump, you'll need a few things handy:

  1. The name of the database you're backing up
  2. A database user with access to the that database
  3. The password for that user

If you don't know these by heart, you can reference the `wp-config.php` file for your WordPress site. The configuration values will look something like this:

/** The name of the database for WordPress */
define('DB_NAME', 'my_db_name');

/** MySQL database username */
define('DB_USER', 'my_db_user');

/** MySQL database password */
define('DB_PASSWORD', 'my_db_password');

With our database info in hand we can run the mysqldump command, which looks like this:

mysqldump -u my_db_user -p my_db_name > /path/to/save/backup_file.sql

If you're not familiar with command line lingo, the "dash-followed-by-letters" are called "flags". Flags give the command-line utility (in this case, mysqldump) answers it needs to run correctly.

The -u flag tells mysqldump to use my_db_user to back up our database. For our purposes, we just need to make sure that my_db_user is allowed to read the database we're trying to back up.

The -p flag tells mysqldump that my_db_user has a password, and we're going to provide that password. Note that it's possible to enter the password directly on the command line like so:

mysqldump -u my_db_user -pmy_db_password my_db_name > /path/to/save/backup_file.sql

Beware: Entering the password this way is considered bad security practice because it makes the password visible to programs that don't need to know about it. We're showing you this use of the -p flag just for completeness, so you know how each of these bits and bobs works.

The > after my_db_name is called an "output redirection symbol", which is just a fancy way of telling mysqldump to send the backup data to a specific file.

To understand output redirection better, let's see what would happen if we didn't add the > to the end of our command. This is what is printed to the screen after running the command without output redirection:

-- MySQL dump 10.13  Distrib 5.5.40, for debian-linux-gnu (x86_64)
--
-- Host: localhost    Database: my_db_name
-- ------------------------------------------------------
-- Server version   5.5.40-0ubuntu0.14.04.1

/* ...snip a zillion SQL commands... */

/*!40101 SET COLLATION_CONNECTION=@OLD_COLLATION_CONNECTION */;
/*!40111 SET SQL_NOTES=@OLD_SQL_NOTES */;

-- Dump completed on 2014-12-31 20:41:58

Whoa! Our whole database backup was printed to the screen!

By using the > operator, we can tell mysqldump where to put our backup, so we can download and use it. In this case, we're telling mysqldump to put our backup here in the file named `/path/to/save/backup_file.sql`.

If your database happens to live somewhere besides localhost (e.g. if you have a separate MySQL server hosting your database), you can use two additional flags to tell mysqldump where to look:

  • -h your.dbserver.com tells mysqldump to connect using the URL your.dbserver.com. You can also use IP addresses.
  • -P 1234 tells mysqldump to use port 1234 - obviously, switch this if your database server is using a different port.

After you run mysqldump, you can find your backup file in the location you specified (in our example, /path/to/save/backup_file.sql). The simplest way to grab it is using your favorite FTP client or by using secure copy from the (local) command line.

scp user@123.123.123.123:backup_file.sql .

How to Restore From a .sql File

Once you have a .sql file handy, you can restore your database using the mysql command-line utility.

Here's the command you'll use:

mysql -u my_db_user -p my_db_name < /path/to/save/backup_file.sql

You'll notice this looks a lot like the mysqldump command we used to create our backup - with a couple of changes:

  1. The first command is mysql instead of mysqldump.
  2. The output redirection symbol (>) has been changed to an input redirection symbol (<). This tells our command to read the .sql file as input for the mysql utility.

All this does is replay the SQL commands written in our .sql file in order to recreate/restore the database to the state it was in when the backup was taken.

Note that mysql can be used with any .sql file - not just those you generate with mysqldump.

Locally, you can also use free software like Sequel Pro to work with your database, including running .sql.

How to Back Up With phpMyAdmin

phpMyAdmin is software that lets you view, edit, and (important for our purposes) export your MySQL database.

  • Recommended for: Development & non-critical sites
  • Difficulty: Not too bad
  • Cost: Free

Many web hosts provide phpMyAdmin access as part of regular hosting plans. If you poke around your hosting account's dashboard, you may find a link to a phpMyAdmin login screen that looks like this:

The username and password is typically the same combo you can find in your `wp-config.php` file (see above).

Once you're logged in, you can select the database you want to back up on the left hand side.

Select the database to back up

Next, you select the Export tab.

By default, phpMyAdmin uses a "Quick" option which is perfect for most use cases. If you're feeling adventurous, there are an awful lot of options you can tweak under the "Custom" section.

Click "Go" to start exporting and downloading your database.

When the download is finished, you'll have a complete backup of your WordPress database.

Beware: If you have a large database or your phpMyAdmin is configured to limit the time allowed for a download, your backup file might be incomplete.

The easiest way to tell if your backup exported successfully is to open it up and scroll waaay to the bottom. The last few lines should have some SQL statements similar to this:

--
-- AUTO_INCREMENT for table `wp_users`
--
ALTER TABLE `wp_users`
  MODIFY `ID` bigint(20) unsigned NOT NULL AUTO_INCREMENT,AUTO_INCREMENT=2;
/*!40101 SET CHARACTER_SET_CLIENT=@OLD_CHARACTER_SET_CLIENT */;
/*!40101 SET CHARACTER_SET_RESULTS=@OLD_CHARACTER_SET_RESULTS */;
/*!40101 SET COLLATION_CONNECTION=@OLD_COLLATION_CONNECTION */;

If you see something different, your backup may be incomplete. If your export timed out, you may see some error messages at the end of your backup file. Or your backup may just cut off at an arbitrary point.

If your backups are incomplete through phpMyAdmin, you may need to tweak your export settings using the "Custom" options or ask your host if they can increase the time limit for PHP requests.

If your host won't help or you just don't want to deal with PHP's quirks, read on to learn about some different (and easier) ways to back up your WordPress database.

How to Restore With phpMyAdmin

It only makes sense that, if you can export a database with phpMyAdmin, you can import one as well. To restore from a database backup, you just need to navigate to the Import tab:

Upload your backup file (.sql or .sql.zip, doesn't matter) using the uploader and click "Go" to restore to backup.

Beware: If you have a large database or your phpMyAdmin is configured to limit the time allowed for script execution, your restore may not complete. If you hit timeout problems, you might want to try tweaking the phpMyAdmin settings or using another method of restoring your database (such as the mysql command-line utility mentioned in the previous section).

How to Back Up by Web Host

In addition to providing access to phpMyAdmin, many hosts provide regular backup services for MySQL databases. The host will take "snapshots" of your database at specific intervals - sometimes weekly, daily, or hourly. Your host may provide web-based access to download the snapshots of your database.

  • Recommended for: Any site
  • Difficulty: Easy
  • Cost: Varies. Some hosts are free, others have a monthly fee.

Availability varies from host to host, and from hosting plan to hosting plan. If you're on a shared hosting plan that costs less than $10 per month, backups are probably not included.

The cost and process for setting up automated backups is different for every host. Here are more details for some of the more common WordPress hosts:

How to Back Up by Plugin

One of the simplest ways to back up your WordPress site is using a plugin.

  • Recommended for: Any site
  • Difficulty: Easy
  • Cost: Varies, depends on the features you need. Free plugins can do basic backups. Paid plugins have convenient features.

There's a cornucopia of backup plugins available, but one of particular interest to developers is WP DB Migrate, and it's paid version WP DB Migrate Pro.

For simple backups, the free version is more than sufficient. Here's how to grab a copy of your database using WP DB Migrate:

  1. Install the WP DB Migrate plugin using the built-in WordPress plugin search & installation interface. Make sure to activate after installation!
  2. Go to Tools → WP DB Migrate on your dashboard.
  3. Select "Download as .zip". If you're simply looking to download a copy of the database for safe keeping, you can remove the find/replace fields:
  4. Click "Migrate" and you'll have a copy of your database saved to your computer.

If you're a developer, it's worth taking a look at the Pro version of WP DB Migrate. With Pro, you're able to synchronize the databases of two WordPress sites.

For example: Say you're working on a live site and you need a copy of the database to do development work. With WP Migrate DB Pro, you can simply synchronize the live version to your development site using the plugin's interface. If you do a lot of WordPress work, it will change the way you develop.

Another notable backup plugin is BackupBuddy by iThemes. While WP DB Migrate has a lot of features that developers can use, BackupBuddy shines for "regular" WordPress users. BackupBuddy can do scheduled backups (much like your web host) and send the backups to a variety of places, such as email, FTP, DropBox, AWS, and others.

There are lots of backup plugins on the WordPress.org repo, and plenty of premium options in addition to BackupBuddy and WP DB Migrate Pro.

Using a Backup Service

Finally, let's look at backing up your WordPress database using a backup service.

Using a backup service is the easiest way to keep backups of your site. Naturally, it's also the most expensive.

  • Recommended for: Live/production sites
  • Difficulty: Easiest
  • Cost: Monthly fee, from $5 to $29 per month.

Here's how it works:

  1. Pay a monthly (or yearly) fee.
  2. Provide the service with access to your site. For some, you install a plugin. For others, you provide login credentials to your host.
  3. Backups are automatically taken on a regular basis and saved to the cloud. Or the backup happens in real time in the case of VaultPress.

Here are some WordPress/MySQL backup services:

Backup services require minimal setup, are constantly backing up your site, include error checking, and (in the case of VaultPress) do security monitoring for your site.

Go Forth and Back Up

Now you're ready to back up your WordPress database. Have a backup method, plugin or service you think we overlooked? Add it in the comments.

How to Scale SVG

The following is a guest post by Amelia Bellamy-Royds. Amelia has lots of experience with SVG, as the co-author of SVG Essentials and author of the upcoming Using SVG with CSS3 and HTML5. Amelia and I both will be speaking on SVG at the upcoming RWD Summit as well! Here, she shares an epic guide to scaling SVG, covering all the ways you might want to do that. It's not nearly as straightforward as scaling raster graphics, but that can be good, because it opens up interesting possibilities.

(more…)

How to Roll Your Own Simple WordPress Podcast Plugin

Let's say you plan to get into podcasting. You have the recording equipment, an interesting topic, and a good voice that other people want to hear. You seem well on your way to filling earbuds everywhere.

Then there's the issue of hosting your podcast. iTunes requires an RSS feed so it can distribute your episodes to subscribers when they're available, but how do you do that? The good news is that there are plenty of ways to host a podcast. For example, you could use a hosting service that provides you storage and distribution in one tidy place, usually for a fee. If you use WordPress and have looked into podcasting, you may have seen all the powerful podcasting plugins that are available there as well.

We're going to skip over those options in this post and see how we can host our own podcast using nothing more than a WordPress site and two additional files. (more…)

Approaches to Media Queries in Sass

The following is a guest post by Eduardo Bouças (@eduardoboucas). Sass allows you to write nested media queries, which is wonderful in itself, but it's possible to abstract things a bit further. Eduardo tried a bunch of different takes on writing media queries in Sass, from the very simple to the complex. This is one of the reasons I like Sass. The language has all the stuff needed for clever folks to write complex solutions to real problems (e.g. this), and the rest of us can just use it. Eduardo ultimately comes up with a good solution that covers all his likes and needs.

(more…)

New Lodge Course Finished: Everything You Need To Know About SVG

Fourty videos by yours truly covering everything from why and when you should be using SVG, to fun things you can do with it, to little gotchas you might encounter. We go over a variety of build tools to help with implementation of icon systems. We cover places to get your hands on SVG. We look at optimizing SVG with a variety of tools. We discuss SVG accessibility, animation techniques, and software available. There is a lot to know!

Naming Things

Speaking of "naming things how you would name them", Paul Lloyd:

Regardless of higher-level conventions, there's no getting away from the fact that, at some point, we're still going to have to name things.

Then goes on to list a slew of considerations for a name, including things like considering industry standards, business-specific names, keeping things obvious, consistent, and extendable, and my favorite, names that you make up because they make sense to you.

... at Clearleft we coined the term gravigation for a navigation bar that was pinned to the bottom of the viewport.

CSS: Just Try and Do a Good Job

Have you ever worried that you're approaching CSS all wrong? That you're missing out on some new approach that makes everything easier and better? That you wish you were more confident about the state of your CSS?

I'm sure we can all empathize with Anna's sentiment here:

(more…)

Positioning Offset Background Images

If you need to position a background-image in CSS 20px from the left and 10px from the top, that's easy. You can do background-position: 20px 10px;. But what if you wanted to position it 20px from the right and 10px from the bottom?

Let's also assume we don't know the exact width and height of the element, which is likely, because fluid layouts and dynamic content. If we did, we could just do a little scratchpad math and use the normal background-position syntax.

A perfectly reasonable request, as they say. Here's some ways to go about it.

(more…)

How to Redirect a Web Page

A redirect is when a web page is visited at a certain URL, it changes to a different URL. For instance, a person visits "website.com/page-a" in their browser and they are redirected to "website.com/page-b" instead. This is very useful if we want to redirect a certain page to a new location, change the URL structure of a site, remove the "www." portion of the URL, or even redirect users to another website entirely (just to name a few).

Let's say we've just moved our website and we want to shut down the old one. However we don't want all those pages from the old site to give a dreaded 404 Not Found. What we need is for those old links to redirect to the same content on our new site.

Here's our example: we want old-website.com/blog/post to redirect to new-website.com/blog/post, along with all the other posts that use that same URL format. Also it would be nice if our redirects would report to search engines that this change is permanent so they should update accordingly.

So how do we that? Well, before we start we need to learn a little about HTTP.

HTTP response codes

Every time we enter a URL or make a request from a browser we're using the Hypertext Transfer Protocol (HTTP). Although this sounds like a really cool name for a sci-fi cop movie it's actually the process by which we request assets such as CSS, HTML and images from a server. After we've sent a request these assets will then give a response like "hey I'm here, let's go!" (response code HTTP 200 OK). There are many different kinds of HTTP response code, the most familiar perhaps being 404 Not Found; web pages can respond with a 404 status but so can any other asset that we request, whether that's an image or any other kind of asset.

Every HTTP response is categorized under a certain three digit number, so 404 Not Found is a 4XX status code to clarify that it's a client error and 200 is in the 2XX category to signify that it's a success message of some kind. We're interested in the 3XX category of HTTP response, like 301 Moved Permanently or 302 Found, because these are the status codes specifically set aside for redirects. Depending on the method we choose we won't necessarily need to know about these codes but it's essential for others.

In our case we'll use a 301 redirect because some web browsers or proxy servers will cache this type, making the old page inaccessible which, in this instance, is exactly what we want.

So how do we actually go about redirecting a web page?

HTML redirects

Perhaps the simplest way to redirect to another URL is with the Meta Refresh tag. We can place this meta tag inside the <head> at the top of any HTML page like this:

<meta http-equiv="refresh" content="0; URL='http://new-website.com'" />

The content attribute is the delay before the browser redirects to the new page, so here we've set it to 0 seconds. Notice that we don't need to set a HTTP status code, but it's important to double check the weird opening and closing of the quotes above (there are quotes within quotes, so they need to be different types and matching).

Although this method is the easiest way to redirect to a web page there are a few disadvantages. According to the W3C there are some browsers that freak out with the Meta refresh tag. Users might see a flash as page A is loaded before being redirected to page B. It also disables the back button on older browsers. It's not an ideal solution, and it's discouraged to use at all.

A safer option might be to redirect the website with JavaScript.

JavaScript redirects

Redirecting to another URL with JavaScript is pretty easy, we simply have to change the location property on the window object:

window.location = "http://new-website.com";

JavaScript is weird though, there are LOTS of ways to do this.

window.location = "http://new-website.com";
window.location.href = "http://new-website.com";
window.location.assign("http://new-website.com");
window.location.replace("http://new-website.com");

Not to mention you could just use location since the window object is implied. Or self or top.

With the location object we can do a lot of other neat stuff too like reload the page or change the path and origin of the URL.

There are a few problems here:

  1. JavaScript needs to be enabled and downloaded/executed for this to work at all.
  2. It's not clear how search engines react to this.
  3. There are no status codes involved, so you can't rely information about the redirect.

What we need is a server side solution to help us out by sending 301 responses to search engines and browsers.

Apache redirects

Perhaps the most common method of redirecting a web page is through adding specific rules to a `.htaccess` on an Apache web server. We can then let the server deal with everything.

`.htaccess` is a document that gives us the ability to give orders to Apache, that bit of software that runs on the server. To redirect users to our new site we'll make a new .htaccess file (or edit the existing one) and add it to the root directory of the old website. Here's the rule we'll add:

Redirect 301 / http://www.new-website.com

Any page that the user visits on the old website will now be redirected to the new one. As you can see, we put the HTTP response code right at the front of the redirect rule.

It's worth mentioning that this kind of redirect only works on Linux servers with the mod_rewrite enabled, an Apache module which lets us redirect requested URLs on the server by checking a certain pattern and, if that pattern is found, it will modify the request in some way. Most hosting companies have this enabled by default, but contacting them is your best bet if there's a problem. If you're looking for more info on mod_rewrite then there's a great tutorial on tuts+. There are also lots of .htaccess snippets here on CSS-Tricks.

Back to our example, if we use the code above then a user will go to "old-website.com/blog/post" and be sent to "new-website.com" which isn't very user friendly because they won't see actual page they asked for. Instead, we'll add the following rule to our `.htaccess` file in order to redirect all those blog posts to the right place:

RedirectMatch 301 /blog(.*) http://www.new-website.com$1

Or perhaps we want to redirect individual pages very specifically. We can add the rules like this:

Redirect 301 /page.html http://www.old-website/new-page.html

And for errors we can redirect users to our 404 page (probably chock full of puns and gifs):

<IfModule mod_rewrite.c>
  RewriteEngine on
  RewriteCond %{REQUEST_FILENAME} !-f
  RewriteCond %{REQUEST_FILENAME} !-d
  RewriteRule .* 404.html [L]
</IfModule>

First we check if we have the mod_rewrite module is available then we can turn it on and, if the file or directory is not found, we send the user off to our 404 page. It's sort of neat that the contents of the page they see will be from the 404.html file whilst the requested URL will remain the same.

If you're not comfortable with messing around with `.htaccess` files and you have WordPress installed then there's a nifty extension that can deal with this stuff for us.

Nginx redirects

If your server is running Nginx as the web server, then in the `nginx.conf` file you can add a server block to handle these redirect requests:

server {
  listen 80;
  server_name old-website.com;
  return 301 $scheme://new-website.com$request_uri;
}

Again we're using the 301 HTTP response and, with the scheme variable, we'll request http:// or https:// depending on what the original website used. It might be a good idea to take a closer look at the HTML5 Boilerplate nginx.conf for best practices on other Nginx related things.

Lighttpd redirects

For those servers running a Lighttpd web server, you make a redirect by first importing the mod_redirect module and using url.redirect:

server.modules  = (
  "mod_redirect"
)

$HTTP["host"] =~ "^(www\.)?old-website.com$" {
  url.redirect = (
    "^/(.*)$" => "http://www.new-website.com/$1",
  )
}

PHP redirects

With PHP we can use the header function, which is quite straightforward:

<?php 
  header('Location: http://www.new-website.com');
  exit;
?>

This has to be set before any markup or content of any other sort, however there is one small hitch. By default the function sends a 302 redirect response which tells everyone that the content has only been moved temporarily. Considering our specific use case we'll need to permanently move the files over to our new website, so we'll have to make a 301 redirect instead:

<?php
  header('Location: http://www.new-website.com/', true, 301);
  exit();
?>

The optional true parameter above will replace a previously set header and the 301 at the end is what changes the response code to the right one.

Ruby on Rails redirects

From any controller in a Rails project, we can quickly redirect to a new website with redirect_to and the :status option set to :moved_permanently. That way we override the default 302 status code and replace it with Moved Permanently:

class WelcomeController < ApplicationController
  def index
    redirect_to 'http://new-website.com', :status => :moved_permanently 
  end
end

In Rails 4 there's any easier way to handle these requests where we can add a redirect in the routes.rb file which automagically sends a 301 response:

get "/blog" => redirect("http://new-website.com")

Or if we want to redirect every article on the blog to posts on the new website we can do so by replacing the above with the following:

get "/blog/:post" => redirect("http://new-website.com/blog/%{post}")

.NET redirects

I've never written anything with the .NET framework before but it looks like there's clear documentation over on Microsoft's Developer Network.

Node.js redirects

Here's a very quick local setup that explains how redirects work with Node. First we include the http module and create a new server, followed by the .writeHead() method:

var http = require("http");

http.createServer(function(req, res) {
  res.writeHead(301,{Location: 'http://new-website.com'});
  res.end();
}).listen(8888);

If you make a new file called index.js and paste the code above and then run node index.js in the command line you'll find the local version of the website redirecting to new-website.com. But to redirect all the posts in the /blog section we'll need to parse the URL from the request with Node's handy url module:

var http = require("http");
var url = require("url");

http.createServer(function(req, res) {
  var pathname = url.parse(req.url).pathname;
  res.writeHead(301,{Location: 'http://new-website.com/' + pathname});
  res.end();
}).listen(8888);

Using the .writeHead() function we can then attach the pathname from the request to the end of URL string. Now it'll redirect to the same path on our new site. Yay for JavaScript!

Flask redirects

With the Flask framework on top of Python we can simply create a route that points to subpages with the redirect function, again 301 has to be an option that is passed in at the end because the default is set to 302:

@app.route('/notes/<page>')
def thing(page):
  return redirect("http://www.new-website.com/blog/" + page, code=301)

If you know of any other tricks to redirect a web page add a comment below and I'll update this post with the latest info.

Sponsor: MyFonts – Subscription-Free Webfonts

MyFonts is the best place to find, try, and buy fonts for your website. Their webfonts are flexible, easy to use, and don't require any monthly fees. Not only that, but you can try any font on your own site free for 30 days.

One thing that you may find appealing about MyFonts is that you host the fonts. That frees you up to use your own CDN, or use your own font loader, or integrate the fonts in whatever fashion works best for you. You have the control.

Looking for a little inspiration? Browse the 50 most popular fonts on the web right now.

Relating to “Designing for Performance” by Lara Hogan

I picked me up a copy of Lara Hogan's new book Designing for Performance (Amazon), as it's a subject I've very interested in these days. As I write this, I'm just off the heels of doing quite a bit of performance related work here on CSS-Tricks as well as on CodePen.

I thought I'd give the book a read, learn some more, and be inspired to do some more. Here's some choice quotes and how they relate to stuff I've been doing, wanting to do, and thinking about.

(more…)

Capability Reporting with Service Worker

We've heard 1,000 times: User Agent sniffing is bad news. We largely do it on the server because we want to know stuff about the client before we even send anything to the client. A worthy goal!

We've talked about this before. Perhaps you serve a little different JavaScript for a different approach to navigation. Or you set a cookie with client side data and use that to serve different image formats depending on support. Maybe you even refresh the page to ensure you have that data. There are even libraries for all this.

Service Workers, a brand new thing on the web, are uniquely qualified to help with this problem as they sit between the client and server and can manipulate requests to pass additional data.

More Elegant Fix for Jumping Scrollbar Issue

If you move from one page of a site without a scrollbar to another with a scrollbar, you'll see a slight layout shift as things squeeze inward a bit to make room for the scrollbar.

A classic fix was html { overflow-y: scroll; } to force the scrollbar all the time. Ayke van Laëthem has found a more elegant solution in html { margin-left: calc(100vw - 100%); } which works because vw accounts for the scrollbar and % doesn't, and... just read it as there are a few more things you'll need to be aware of anyway.

Pretty sweet for a first blog post Ayke!

icon-closeicon-emailicon-linkicon-menuicon-searchicon-tag