Inline SVG vs Icon Fonts [CAGEMATCH]

If you’re building an icon system for a site, you have some options. If you know the icons need to be raster images, then you’ll likely be using CSS sprites. If the icons will be vector images (much more common these days), you have some options. Two of those options are using inline SVG and using icon fonts.

Let’s compare.

 

Icons are Vector

There are big advantages to vector icons: resizable up and down without losing quality, extra sharp on retina displays, and small file size among them.

Icon Font Inline SVG
Browsers consider it text, so the icons are anti-aliased as such. Can lead to icons not being as sharp as you might expect. Straight up vector

In a recent personal example, while converting some icons from fonts to SVG on CodePen, some of the font icons were noticeably less sharp than the ones I converted over.

CSS Control

Icon Font Inline SVG
You can control the size (via font-size), color, shadows, rotation, etc. via CSS. You have all the same CSS control as with a font, but better, because you can 1) control individual parts of a multi-part icon and 2) use SVG-specific CSS like stroke properties.

Positioning

Icon Font Inline SVG
It can be frustrating to position a font icon. The icons are inserted via pseudo element, and it depends on line-height, vertical-align, letter-spacing, word-spacing, how the font glyph is designed (does it naturally have space around it? does it have kerning information?). Then the pseudo elements display type affects if those properties have an effect or not. SVG just is the size that it is.
See how the pseudo element box isn’t quite where the glyph actually is.
The SVG box is the size of the SVG.

Weird Failures

Icon Font Inline SVG
An icon font might fail because 1) it’s being loaded cross-domain without the proper CORS headers and Firefox doesn’t like that 2) for any reason, the font file fails to load (network hiccup, server failure, etc) 3) There is some weird Chrome bug that dumps the @font-face and shows a fallback font instead 4) Surprising browser doesn’t support @font-face.

Font failures are pretty common for a variety of reasons.

Inline SVG is right in the document. If the browser supports it, it displays it.

Semantics

Icon Font Inline SVG
To use responsibly, you’re injecting the icon via a pseudo element on an (empty) <span>. Either bad or no semantics, depending on how you feel about that kind of thing. Icons are little images. The semantics of <svg> says “I’m an image.” Seems better to me.

Accessibility

Icon Font Inline SVG
You have to be quite careful with icon fonts to make sure you do it in an accessible way. You should basically do everything in this article. You’re always fighting to make sure that the icon itself isn’t read (but something else is) and that hard-to-detect fail states are handled. I’m no expert, but research suggests using the proper combination of elements and attributes (<title>, <desc>, and aria-labelledby) you can convey good information across the browser specturm. Plus no weird fail states.

Ease of Use

Icon Font Inline SVG
Using a pre-created icon font was never particularly responsible (too many unused icons). Creating your own icon font was never overly comfortable. I think the best were Pictos Server (limited to Pictos icons) and IcoMoon (free login to save projects). Fontello has an API I didn’t see it used to make a good build tool. The inline SVG system is easier because you can do it all by hand if needed. Or use a tool like IcoMoon (exports either way). Or use a build tool.

Browser Support

Icon Font Inline SVG
Very deep. Even IE 6. Decent, but problems are IE 8- and Android 2.3-. Fallbacks doable but not wonderful.

Winner

It all comes down to browser support. If you can go IE 9+ / Android 3+, inline SVG is better at pretty much everything than icon fonts. If you need the deeper browser support, I feel like an inline SVG fallback would be too big of a pain to be worth it (maintaining a PNG copy, inserting an additional element to display PNG version, hiding SVG element… it’s weighty).


Inline SVG vs Icon Fonts [CAGEMATCH] is a post from CSS-Tricks

from CSS-Tricks http://ift.tt/1rezNuc

Stripes in CSS

Stripes are pretty easy to do in CSS these days. CSS gradients via the background-image property really got our back. I thought I’d document some varitions in one easy to reference place.

Normal Colored Diagonal Stripes

Diagonal stripes are easy to pull off thanks to repeating-linear-gradient():

background: repeating-linear-gradient(
  45deg,
  #606dbc,
  #606dbc 10px,
  #465298 10px,
  #465298 20px
);

Rather than the very last color-stop being 100% (or nothing, which means 100%) it’s a fixed value. Beyond that, it just kinda starts over. This is how I think of it (zoomed in):

See the Pen epfEc by Chris Coyier (@chriscoyier) on CodePen.

Gradient Diagonal Stripes

If you make the background a regular linear-gradient(), and then make half the stripes totally transparent using repeating-linear-gradient(), it can appear as if the stripes have gradients. Because of multiple backgrounds (and stacking order), you can do that all together on a single element:

background: 
  /* On "top" */
  repeating-linear-gradient(
    45deg,
    transparent,
    transparent 10px,
    #ccc 10px,
    #ccc 20px
  ),
  /* on "bottom" */
  linear-gradient(
    to bottom,
    #eee,
    #999
  );

See the Pen xhkpD by Chris Coyier (@chriscoyier) on CodePen.

Stripes Over Image

Perhaps a texture? Any image will work. You could reveal part of the image by making some stripes fully transparent and some fully opaque. Or, any combination. Again multiple backgrounds allows this to all happen on the same element.

background: repeating-linear-gradient(
  45deg,
  rgba(0, 0, 0, 0.2),
  rgba(0, 0, 0, 0.2) 10px,
  rgba(0, 0, 0, 0.3) 10px,
  rgba(0, 0, 0, 0.3) 20px
),
url(http://ift.tt/1q0oPpR);

See the Pen gaKyv by Chris Coyier (@chriscoyier) on CodePen.

Any Direction, Any Angle

It doesn’t have to be exactly 45degrees. That’s part of the beauty of the repeating-linear-gradient(). It’s not like this perfect rectangle that has to line up and repeat, it’s just a set of drawing instructions that repeats.

background: repeating-linear-gradient(
  -55deg,
  #222,
  #222 10px,
  #333 10px,
  #333 20px
);

See the Pen qfHmw by Chris Coyier (@chriscoyier) on CodePen.

Straight Stripes (slightly better browser support)

There is a super old syntax for CSS gradients that used -webkit-gradient() (note the no “linear” or “radial”). Basically: Safari 4, Chrome 1-9, iOS 3.2-4.3, Android 2.1-3.0. Old stuff. Those browsers don’t support repeating gradients. But you could kinda fake it, especially for straight stripes, by making a small rectangle of background via background-size, drawing the stripes in there, and having it repeat naturally like background-image does.

background: linear-gradient(
  to bottom,
  #5d9634,
  #5d9634 50%,
  #538c2b 50%,
  #538c2b
);
/* The rectangle in which to repeat. 
   It can be fully wide in this case */
background-size: 100% 20px;

See the Pen uxJrf by Chris Coyier (@chriscoyier) on CodePen.

If you wanted to get crazy, you could transform: rotate() some element with these straight stripes and cut off the overflow, in which to replicate diagonal stripes with deeper browser support. Sounds like a lot of work.

Vertical Stripes

You could use the same method as above for vertical stripes too. Or, just use repeating-linear-gradient():

background: repeating-linear-gradient(
  to right,
  #f6ba52,
  #f6ba52 10px,
  #ffd180 10px,
  #ffd180 20px
);

See the Pen oCpEu by Chris Coyier (@chriscoyier) on CodePen.

Just to be clear, with repeating-linear-gradient() you are best off doing a -webkit-repeating-linear-gradient() as well as the unprefixed one, if you’re, you know, prefixing buy yourself which you shouldn’t.

Radial Stripes

Who says they have to be straight lines eh? Radial gradients can be repeating-linear-gradients():

/* Note the RADIAL */
background: repeating-radial-gradient(
  circle,
  purple,
  purple 10px,
  #4b026f 10px, 
  #4b026f 20px
);

See the Pen AEymd by Chris Coyier (@chriscoyier) on CodePen.

Funky Town

Sometimes rounding errors (maybe?) or other kinda rendering funkiness happens.

Whattyagonnado. I suspect it will get better over time.

All together now.


Stripes in CSS is a post from CSS-Tricks

from CSS-Tricks http://ift.tt/1q6yltm

Hassle Free Responsive Images for WordPress

The following post is guest co-authored by Tim Evko (@tevkor). WordPress has a built-in media uploading system. When you upload an image, it automatically creates and saves different versions of it. Tim will show us how we can customize and exploit that ability to help us with responsive images in content.

If you’re like me, and you’re tasked with building responsive website that’s relatively easy to update, WordPress is most often the CMS you will be building that website on. If you’re more like me, you probably skipped over a responsive image solution in favor of making things easier for whomever will be doing the updating. Fortunately, with a few lines of PHP and some JavaScript, you can now add automatic responsive image functionality to your WordPress site.

Here I’ll show you how to add support for responsive images to your WordPress site in the form of a small WordPress plugin.

The Markup we ultimately want

We’ll be using the Picturefill library here. For now, we’ll use the markup that library suggests, which closely mimics what the <picture> element will soon be.

<span data-picture data-alt="A giant stone face at The Bayon temple in Angkor Thom, Cambodia">
  <span data-src="small.jpg"></span>
  <span data-src="medium.jpg"     data-media="(min-width: 400px)"></span>
  <span data-src="large.jpg"      data-media="(min-width: 800px)"></span>
  <span data-src="extralarge.jpg" data-media="(min-width: 1000px)"></span>

  <!-- Fallback content for non-JS browsers. Same img src as the initial, unqualified source element. -->
  <noscript>
    <img src="small.jpg" alt="A giant stone face at The Bayon temple in Angkor Thom, Cambodia">
  </noscript>
</span>

Eventually we can update all this to use the <picture> syntax once Picturefill is ready for it.

What we’re not going to do is use that markup directly in blog posts, we’re going to get WordPress to help us with that.

The Theme

All you need to do in your theme is make sure this one-liner is present in its functions.php file:

add_theme_support('post-thumbnails');

This will ensure that your theme gives WordPress permission to resize the uploaded images. Without it, the plugin won’t work.

The Plugin

This makes sense to do as a WordPress plugin, because we’ll want to keep it active no matter what theme is active. We can make it a folder with a PHP file in there to be the plugin code itself, and a copy of the Picturefill library:

Adding the library

Queue it up responsibility:

function get_picturefill() {
  wp_enqueue_script('picturefill', plugins_url( '/js/picturefill.js', __FILE__ ));
}
add_action('init', 'get_picturefill');

That will ensure WordPress loads up this JavaScript library on the front end.

Define sizes

Tell WordPress what size images you want created upon uploading:

add_image_size('large-img', 1000, 702);
add_image_size('medium-img', 700, 372);
add_image_size('small-img', 300, 200);

You can set this up however you like. add_image_size has a variety of parameters you can adjust. In the case of a 1024×768 bunny rabbit JPG I uploaded, a bunch of versions get created:

The 936×702 one was created because we specified we wanted one with a max of 702 height. The 150×150 one was created because WordPress automatically makes a square thumb of that size.

Making a [shortcode]

Let’s extend this plugin, giving it some real functionality, by making a responsive images shortcode. That way we can put this right in the post content:

[responsive imageid="12" size1="0" size2="500" size3="1000"]

and it will output the markup we need for Picturefill.

We’ll split this up into two functions. One to define the shortcode and what HTML to output, and one specifically to loop through and output the image sources.

function getPictureSrcs($image, $mappings) {
  $arr = array();
  
  // Loop through all of our images sizes and store each one of them as a php variable, In which each image size corresponds to a specific type. Mappings is defined later on
  foreach ($mappings as $size => $type)
  {
    // we're using 'wp_get_attachment_image_src();' to get the image we uploaded
    $imageSrc = wp_get_attachment_image_src($image, $type);
    $arr[] ='<span data-src="'. $imageSrc[0] . ' "data-media="(min-width:'. $size .'px)"></span>';
  }
  return implode($arr);
}
  
// Enable the [responsive] shortcode
function responsiveShortcode($atts) {

  extract(shortcode_atts(array(
  // In this array, we're creating the parameters to be passed into the shortcode tag  
    'imageid'    => 1,
    // You can add more breakpoint sizes for your shortcodes here. The current values being assigned here are our default values, which the shortcode will ovveride
    'size1' => 0,
    'size2' => 600,
    'size3' => 1000,
  ), $atts));

  // Here we're defining our mappings to be stored as variables, so we can declare whatever size we want in our shortecode 
  $mappings = array(
    $size1 => 'small-img',
    $size2 => 'medium-img',
    $size3 => 'large-img'
  );

  // Then we pass in the responsive image function, and print out the new responsive image tag with our shortcode variables included
  return 
    '<span data-picture>'
      . getPictureSrcs($imageid, $mappings) .
      // this noscript tag contains our default image for old / JavaScript-less browsers, and we're using size2 as our default
      '<noscript>' . wp_get_attachment_image($imageid, $size2) . '</noscript>
    </span>';
}
add_shortcode('responsive', 'responsiveShortcode');

Ideally you define your breakpoints in the plugin here and then don’t pass them at all in the shortcode, like:

[responsive imageid="12"]

Then only use the shortcode attributes in the rare cases you need to override the breakpoints.

Altering the Media Uploader output

This shortcode will be tremendously useful (remember we can even adjust the markup to be the correct <picture> in the future programmatically). But, how do we know the image ID to use? The Media Uploader UI doesn’t make that information available. It knows that ID though, and with a simple filter we can adjust what gets sent to the editor:

function responsive_insert_image($html, $id, $caption, $title, $align, $url) {
  return "[responsive imageid='$id' size1='0' size2='600' size3='1000']";
}
add_filter('image_send_to_editor', 'responsive_insert_image', 10, 9);

Now selecting and inserting an image from the editor will work like this:

That’ll do it! Here you can see it working:

More you can do

  • If you’re looking for a wider range of support, consider installing Matchmedia.js as well. It will make @media queries start working in older browsers, which then automatically makes Picturefill work as well.
  • Rather than use shortcodes or adjust the media uploader output, you could make this work with a special image field via Advanced Custom Fields.
  • You could adjust the markup to allow for align-* as WordPress likes to do. Or with <figure> and <figcaption> elements. Also, alt tags.
  • You could have the settings for the breakpoints be settable via UI that the the plugin creates, rather than hard coded into the plugin.

Here’s the GitHub repo if you want to contribute.


Hassle Free Responsive Images for WordPress is a post from CSS-Tricks

from CSS-Tricks http://ift.tt/1hlqfGb

Spring-cleaning Unused CSS

Addy Osmani intros a Grunt task for removing unused CSS from your stylesheet before serving it.

While this is certainly a worthy goal, I look at the quotes from people who reduced their stylesheets by 3/4 or more and I’m like holy crap what kinda shop are you running over there?! I know “test, don’t guess”, but I’d guess that pretty close to 0% of the styles I write are unused. I’m sure HTML changes over time make a orphaned rule here and there, but I’d guess that is largely insignificant.

If you’re going to do this, make sure you run it against lots (if not all) of your pages so you aren’t removing selectors that are in use, just not on every page. I know I write minor styles all the time that make their way into the global stylesheet since that is cached and used anyway.

Direct Link to ArticlePermalink


Spring-cleaning Unused CSS is a post from CSS-Tricks

from CSS-Tricks http://ift.tt/1for8xJ

Rotated Table Column Headers

Say you have a table header (i.e. <th>) of “Number of Howler Monkey Species by Country” and the data in the corresponding <td> is like “3”. That’s an awkward mismatch of width.

Awkward

Perhaps not a huge problem for two columns, but if you had 20 that would be very hard to navigate and a poor use of space. A better use of space is to rotate the headers so that the column width can be much narrower.

Rotating 90-degrees is too far though. It makes it hard to read.

Interestingly, we get just about the same amount of space saving if we rotate the headers 45 degrees instead, and they are much easier to read.

The Trick

There are a couple of tricks here.

We’re going to need to user transform: rotate() to angle the headers. Chrome/Safari let you do that right on the <th>, but I had trouble with the text disappearing in Firefox that way, so let’s do that within a nested <div>. That

we’ll force to be the width we want the column to be (it also didn’t work to force the cell narrow directly). We’re going to need another nested element as well, so…

<th class="rotate"><div><span>Column header 1</span></div></th>
th.rotate {
  /* Something you can count on */
  height: 140px;
  white-space: nowrap;
}

th.rotate > div {
  transform: 
    /* Magic Numbers */
    translate(25px, 51px)
    /* 45 is really 360 - 45 */
    rotate(315deg);
  width: 30px;
}
th.rotate > div > span {
  border-bottom: 1px solid #ccc;
  padding: 5px 10px;
}

Note the magic numbers there. I bet some of you are smart enough to figure out the mathematical relationship to all the other numbers going on in there. In fact, my example started out life as a fork of Jimmy Boney’s Column Header Rotation article. I was able to do it without the skew() stuff he was doing which I think makes it a bit simpler, but he also had figured out some math stuff using tan() and cos() which might be a good starting point if you start digging in yourself.

Fallback

If you go down this road, you might wanna make sure you aren’t applying rules that screw up the table if the transforms don’t work. Modernizr can test for that and apply support/non-support classes to the <html> element, so you can write stuff like:

/* These aren't needed and will be weird if transforms don't work */
.csstransforms & th.rotate {
  height: 140px;
  white-space: nowrap;
}

How you want to do the fallback is up to you, but it could be worse than just having the table be super wide:

My final demo has this in place.

Demo

See the Pen Rotated Table Headers by Chris Coyier (@chriscoyier) on CodePen.

It’s in Sass in case you want to fork it and figure out some awesome way to use variables and math and stuff to make it more adaptable.


Rotated Table Column Headers is a post from CSS-Tricks

from CSS-Tricks http://ift.tt/QkOChX

Hatin’ on Web Tech

This article “Shadow DOM” by Steven Wittens is only vaguely about the Shadow DOM. It’s mostly about how awful everything is. HTML sucks, CSS sucks, the DOM sucks, SVG sucks, MathML sucks… I don’t want to pick on Steven. He is, without a doubt, many (many) times smarter than I am and has well articulated points. Let’s go wider.

I see this regularly from people who have been at this a long time and are very smart. They develop a dislike of the systems we have to work with. They see all the warts, mistakes, and especially what they see as deep systemic flaws or historical turns down the wrong path. This is all made worse as we trapse forwards, building upon these perceived cracks in the foundation.

They always have very good points. It’s hard to do anything but nod, because they are right, the web does some whacky stuff and has failed us in many ways. Wouldn’t it be wonderful if we could throw it all away and work with some new perfectly designed system that meets everyone’s modern needs. Sure, of course it would. Do you want to live in your town or a utopian village? I’ll take utopia.

Obligatory follow up sentence: but utopia doesn’t exist!

There is no alternate layout language for the web. There is no alternative way to deliver accessible content. There is no better replacements vying for the lead here. That’s because that’s a monumental task. Any contender would need to:

  1. Develop a new system for everything is empirically better.
  2. Get a world of developers to agree that this new system is better and demand it.
  3. Get standards bodies (or something like it) to support it so there is oversight and an independent source of implementation information.
  4. Get all browsers to agree and implement it perfectly.

lol right.

All those things are so insurmountably difficult that it’s no wonder it is rarely even attempted. I’d argue that #1 is the hardest. There are plenty of flaws with our current system, but imagine starting from scratch with something this complex.

I feel like what is going on now in web tech is that these problems are trying to be solved on a smaller scale.

It sure is a bummer HTML is our content, but also responsible for semantics, right? It would be nice to do whatever we wanted in there and not worry we were hurting semantics. Hopefully Shadow DOM can help with that. Maybe it can also help with CSS being to over-arching when you don’t want it to be.

Maybe flexbox, grid layout, and regions can be the truly powerful and intuitive layout system we’ve always needed, without the accessibility issues inherent to tables.

SVG isn’t perfect, but maybe it’s still better than using a raster image format for a vector image? Maybe SVG has the potential to help with icon systems on sites in a better way? Maybe we can start using a new image format that increasingly works with modern browsers.

Maybe preprocessors can be a solution to ease authoring of these complex languages and reduce complexity?

Perhaps we can extend the web right now how we might want to see it, using existing tech.

These things are proving that we can make the web better. We can do it slowly. We can do it with the help of standards bodies. We can educate developers and change their thinking over time. We can use the browsers already out there, so we don’t need to fight public behavior.

I think that sounds nice. And I don’t think we have much of a choice.


Hatin’ on Web Tech is a post from CSS-Tricks

from CSS-Tricks http://ift.tt/NVVUXm