LightBlog
Showing posts with label CSS. Show all posts

There's an update to this article that recommends a slightly better approach. You can find it here:  Font Loading Revisited with F...

Image result for speed up your site
There's an update to this article that recommends a slightly better approach. You can find it here: Font Loading Revisited with Font Events
Using @font-face to load custom web fonts is a great feature to give our sites a unique and memorable aesthetic. However, when you use custom fonts on the web using standard techniques, they can slow down page load speed and hamper performance—both real and perceived. Luckily, we've figured out some methods to apply them carefully to ensure your site correctly balances usability, performance and style.

The problem with @font-face

The CSS @font-face declaration is the standard approach for referencing custom fonts on the web:
/* Define a custom web font */
@font-face {
  font-family: 'MyWebFont';
  url('webfont.woff2') format('woff2'), 
  url('webfont.woff') format('woff'), 
  url('webfont.ttf')  format('truetype'),
}
/* Use that font in a page */
body {
  font-family: 'MyWebFont', sans-serif;
}
Clean and simple, but unfortunately most browsers’ default handling of @font-faceis problematic. When you reference an external web font using @font-face, most browsers will make any text that uses that font completely invisible while the external font is loading [Fig. 1, below]. Some browsers will wait a predetermined amount of time (usually three seconds) for the font to load before they give up and show the text using the fallback font-family. But just like a loyal puppy, WebKit browsers (Safari, default Android Browser, Blackberry) will wait forever (okay, often 30 seconds or more) for the font to return. This means your custom fonts represent a potential single point of failure for a usable site.
A screenshot of Mobile Safari where the webfont is invisible


FIG 1: Screenshot of a webpage loading in iOS Safari, with text invisible until custom fonts finish loading.





Even when the fonts do load correctly, custom fonts slow down the perceived speed of a site significantly because a page full of invisible text isn't exactly usable. Sure, once the first page is visited, the custom fonts are cached and display quickly, but perceived speed for the first page view is critical. If we can't paint a usable page within a few seconds, a lot of visitors will drop off.
For example, Fig. 2 shows a webpagetest.org timeline illustrating how a site would look when accessed on a stable 3G connection if it were using the default font loading behavior, note that the custom @font-face text does not appear until a full second after first render:
A shaped 3G film strip showing how the fonts are invisible while loading
FIG 2: Timeline of our website using standard custom font loading. On a 3G cable connection, fonts delay by 1 full second.
Our users want a usable page as quickly as possible—within a second, ideally—so we want visible text as close to that goal as we can. There are several approaches you can take to work around these issues, but the most important thing you can do is to move away from the default way we’re told to load fonts.
Here are the criteria you should use when evaluating a font loading approach:
  • The CSS request containing your font-face definition(s) should not block page render. Instead of referencing your fonts via <link>s in the <head> or via@import statements in an external stylesheet, try to load your fonts and font content asynchronously. Don’t worry, we’ll show you how.
  • Font requests should be set up to ensure the fallback text is visible while loading, avoiding the Flash of Invisible Text or FOIT.

The Filament Group Way™ to load fonts

To optimize for the first view, we first make sure we have a native font in our font-family stack behind our custom web font, in this case font-family: Open Sans, sans-serif;. This sets the stage for how our text will render using the fallback experience while the font is loading using our new font loading method. JavaScript can then used to detect the best font format to use (WOFF2, WOFF, TTF) and asynchronously load a stylesheet that contains all the fonts embedded as a series of data URIs. This is a bit unconventional but it allows us to load all the custom fonts as a single HTTP request, which is nice both for minimizing reflows (all fonts arrive at once) and for reducing HTTP requests in general. To take this even further, after requesting a font, we set a cookie to flag that the custom fonts are now cached so we can avoid the flash of the default fonts on subsequent pages.

STEP 1: PREPARE YOUR FONTS

Custom fonts can be very heavy so the first order of business is minimizing the number of fonts we need to load in the first place. Remember each weight (regular, light, bold) and variant (regular italic, bold italic) of a typeface is a separate font file which can add up quickly. Try to keep the total number of custom fonts to less then five, but we usually shoot for 2-3 if we can.
To further streamline your font delivery, use a technique called subsetting that allows you to remove characters and symbols from a font that you don't need. TheFontSquirrel tool makes this pretty easy.

STEP 2: PREPARE THE FONT STYLESHEETS

Encoding fonts to Data URIs
Let's say we’re using the Open Sans typeface with two different weights: 400 and 700 (Bold). To support the widest range of browsers, we'll need each font in three different formats: WOFF2, WOFF, and TrueType (TTF):
  • OpenSans-Regular.ttf
  • OpenSans-Bold.ttf
  • OpenSans-Regular.woff
  • OpenSans-Bold.woff
  • OpenSans-Regular.woff2
  • OpenSans-Bold.woff2
If you’re missing one or more of these formats, upload it into the Font Squirrel Web Font Generator to create the others for you.
Take each of these font files and encode them into a Data URI so we can embed them into a stylesheet. If you aren’t familiar with how to create a Data URI, there are many options: SASS (Compass)PHPonline generators, or by using OpenSSL on the command line (openssl base64 -in filename.woff).
Copy the output into three different stylesheets, one CSS file for each font format: WOFF2 (data-woff2.css), WOFF (data-woff.css), and TTF (data-ttf.css for Android). Here is what an example of data-woff.css might look like:
@font-face {
  font-family: Open Sans;
  src: url("data:application/x-font-woff;charset=utf-8;base64,...") format("woff");
  font-weight: 400;
  font-style: normal;
}

@font-face {
  font-family: Open Sans;
  src: url("data:application/x-font-woff;charset=utf-8;base64,...") format("woff");
  font-weight: 700; /* Bold */
  font-style: normal;
}
Inside of the other font format files, the src: url(...) format(...) should match up with the specific format. For example, inside data-woff2.css you’d useurl("data:application/font-woff2;charset=utf-8;base64,...") format("woff2"); and for data-ttf.css you’d use url("data:application/x-font-ttf;charset=utf-8;base64,...") format("truetype");.

STEP 3: SET UP THE STYLESHEET LOADER

Once a font file is prepared, we’ll need to load it asynchronously to ensure no FOIT occurs. We use our our loadCSS utility to handle this part. For example, here's how we can use loadCSS to load our WOFF2 fonts:
loadCSS( '/url/to/data-woff2.css' );
Of course, we want to load the appropriate font stylesheet for each browser that visits the site. How do we determine which format to use? By default we use the WOFF format because of its breadth of browser support. If a browser passes aWOFF2 feature test, we use WOFF2 instead because its file size is normally about 30% smaller. If we can reasonably guess that the current browser is the defualt Android Webkit Browser (not Chrome), we switch to TTF for Android 4.X support. Keep in mind that if an incorrect format is loaded, the browser will simply fallback to using default local fonts.
Here’s an excerpt of the JavaScript we use to load our fonts. We recommend placing this JavaScript inline in a script element in the head of your HTML to kick off the font request as soon as possible (more about how we configure the head of our pages with Enhance.js):
// NOTE!! The WOFF2 feature test and loadCSS utility are omitted for brevity

  var ua = window.navigator.userAgent;

  // Use WOFF2 if supported
  if( supportsWoff2 ) {
    loadCSS( "/url/to/data-woff2.css" );
  } else if( ua.indexOf( "Android 4." ) > -1 && ua.indexOf( "like Gecko" ) > -1 && ua.indexOf( "Chrome" ) === -1 ) {
    // Android's Default Browser needs TTF instead of WOFF
    loadCSS( "/url/to/data-ttf.css" );
  } else {
    // Default to WOFF
    loadCSS( "/url/to/data-woff.css" );
  }
The browser will not make the text invisible while our Data URI CSS file is loading asynchronously. This means that the fallback text will be readable while our web fonts are loading—even if the request hangs and never returns.
Figure 3 below shows the change: With this technique we get readable immediately on first render. This is what we’re going for (3G timeline):
A shaped 3G film strip showing how the fallback is visible while the font is loading
FIG 3: Success! Timeline of our website using our recommended custom font loading. On a 3G cable connection, fonts appear on first render.
For more detail on this approach, we’ve also provided a live demo and the source code on GitHub.

Using Cookies to make this Smarter

Up to this point, we've focused on preparing and loading our custom fonts responsibly so we can show the fallback font while we wait for the custom fonts to load. When these fonts finally do load, the browser swaps out the native fonts for custom fonts. This will cause a repaint and usually has small layout shifts since the fonts are slightly different sizes. We think this font shift is a small tradeoff to show a usable page seconds faster on the initial visit but it can be annoying once you start navigating around.
To remedy this, we use cookies to track if the custom fonts are already downloaded and in the browser's cache. If they are, we show the custom fonts right off the bat to avoid any shifting around.
Instead of the font loader above we’ll want to use a different loader, shown below. We’ll want to add a cookie to flag that the fonts are now cached. In addition to noting that the fonts are cached, the cookie also contains the URL to the specific font format being used as well (data-woff2.cssdata-woff.css, or data-ttf.css). Don’t forget to include the Filament Group cookie utility:
// NOTE!! The WOFF2 feature test, loadCSS, and cookie utility are omitted for brevity

  // Default to WOFF
  var fontFileUrl = "/url/to/data-woff.css",
    ua = window.navigator.userAgent;

  // Use WOFF2 if supported
  if( supportsWoff2 ) {
    fontFileUrl = "/url/to/data-woff2.css";
  } else if( ua.indexOf( "Android 4." ) > -1 && ua.indexOf( "like Gecko" ) > -1 && ua.indexOf( "Chrome" ) === -1 ) {
    // Android's Default Browser needs TTF instead of WOFF
    fontFileUrl = "/url/to/data-ttf.css";
  }

  // ADDED: Make sure the fonts are not yet cached
  if( fontFileUrl && !cookie( "fonts" ) ) {
    // Load the fonts asynchronously
    loadCSS( fontFileUrl );

    // ADDED: Set the cookie indicating the fonts are cached
    // The cookie also denotes what format is used (WOFF, WOFF2, or TTF)
    cookie( "fonts", fontFileUrl, 7 );
  }
Then add the following markup block to our <head> updating the values of each of the fontsWOFFfontsWOFF2fontsTTF variables with the URL of the Data URI CSS font format file. Note that when the cookie has been set and contains the value of the URL of the font format we want to load, a blocking link element is inserted into the page pointing to the Data URI CSS file. However, the blocking behavior of this request is okay because the CSS request has already been cached by the browser and it will load almost immediately.
<!--#set var="fontsWOFF" value="/css/data-woff.css" -->
<!--#set var="fontsWOFF2" value="/css/data-woff2.css" -->
<!--#set var="fontsTTF" value="/css/data-ttf.css" -->
<!--#if expr="$HTTP_COOKIE=/fonts\=$fontsWOFF/" -->
  <link rel="stylesheet" href="<!--#echo var="fontsWOFF" -->">
<!--#elif expr="$HTTP_COOKIE=/fonts\=$fontsWOFF2/" -->
  <link rel="stylesheet" href="<!--#echo var="fontsWOFF2" -->">
<!--#elif expr="$HTTP_COOKIE=/fonts\=$fontsTTF/" -->
  <link rel="stylesheet" href="<!--#echo var="fontsTTF" -->">
<!--#endif -->
The code above requires Apache Server Side Includes but you could do something similar with any server side language.
For more detail on this approach using cookies, we’ve also provided a live demoand the source code on GitHub.

Wrapping Up

Using web fonts can really be a great way to improve the quality of our web work, but using web fonts with the default loading behavior can be very detrimental to our page’s perceived performance. The above method works great to eliminate the text invisibility usually associated with @font-face and make our pages usable much faster. We hope you (and your visitors) find it useful!

Below is a complete guide of HTML codes that you can copy and paste for use on your own blog or website. Although I like to insist on b...


Below is a complete guide of HTML codes that you can copy and paste for use on your own blog or website. Although I like to insist on bloggers taking the time to learn how to write these codes and know what each part of them does, sometimes you need a code in a pinch! Be sure to view the other tutorials on this site for more in-depth demonstrations and explanations of coding.


Quick jump:

Text Formatting

Headings

Defines an important heading in your text. You can use <h1> to <h6>, with the highest number resulting in the smallest font size.
<h1>Your important heading</h1>

Aligned Heading

Aligns your heading using a little bit of CSS. You can use “left”, “right”, or “justify” in place of “center” below:
<h1 style="text-align:center;">Your aligned heading</h1>

Paragraphs

Inserts a paragraph break. Defines each paragraph.
<p>Your paragraph here</p>

Aligned Paragraph

Aligns your paragraph using a little bit of CSS. You can use “left”, “right”, or “justify” in place of “center” below:
<p style="text-align:center">Your paragraph text is aligned</p>

Line Breaks

Line breaks are used instead of paragraphs, when you want to create a new line without starting a new paragraph.
The end of your sentence.<br />

Bold Text

Makes the weight of your font bold
<b>Your bold text</b>

Strong Text

Same look as bold text, but is semantic. Instead of it being simply a style, strong text shows how the text should be read or understood.
<strong>Your strong text</strong>

Italic Text

Makes your text italicized
<i>Your italic text</i>

Emphasized Text

Same look as Italic text in HTML, but is semantic. Specifies that the text should be emphasized when read.
<em>Your emphasized text</em>

Underlined Text

Underlines your text
<u>Your underlined text</u>

Strike-through

Places a line through your text to strike it out.
<s>Your text here</s>

Font Family

Changes the font of the text using a little CSS. You can change the font to any web safe font or Google web font:
<span style="font-family: Arial, Helvetica, sans-serif;">Your new font</span>

Font Size

Changes the size of the font using a little CSS. You can use px, em, or a percentage. Here is an example with px:
<span style="font-size:16px;">Your font in a new size</span>

Font Color

Changes the color of your font to any hex color value of your choice:
<span style="font-color:#030303;">Your new font color</span>

Highlighted Text

Highlights the text with a background color using a little CSS:
<span style="background-color:#C2F2CA">Your highlighted text</span>

Block Quotes

Useful when quoting someone or when you need a particular part of your text to stand out.
<blockquote>Your quoted text here</blockquote>

Links

Basic Text Link

Use to add a link to specific text or a word. Replace the http://www.yourlink.com with your own link:
<a href="http://www.yourlink.com">Your linked text</a>

Open Link in New Tab

Used to open the link in a new window or tab instead of in the same web page:
<a href="http://www.yourlink.com" target="_blank">Your linked text</a>

Link To An Email Address

Opens the user’s email program to quickly send an email to the address supplied. Replace the email address with your own:
<a href="mailto:you@youremailaddress.com">Your email address or link</a>

 Link To An Email Address With Subject Line

Useful if you want the email to have a specific subject when a user clicks your link. Use %20 in place of any spaces and replace the text with your own subject line:
<a href="mailto:you@youremailaddress.com?subject=Your%20Email%20Subject">Your email address or link</a>

Anchored (“Jump”) Link

For jumping to a particular part of a page with the click of a link. This happens in two parts. First, include the code below wherever you want the user to end up when they click the link, for example, at the top of the post. Name it something unique:
<a name="backtotop"></a>
Then, add the anchor to your link that the user will click on to jump to that section:
<a href="#backtotop">Back to top</a>

Images

Basic Image

Include an image in your post. Replace the image URL with your own URL. You will need to have this image uploaded somewhere online. Describing your image helps with SEO:
<img src="http://www.yoursite.com/yourimage.jpg" alt="describe this image"/>

Image Link

For adding a link to a certain image. Replace the image URL and link with your own:
<a href="http://www.yourlink.com"><img src="http://www.yoursite.com/yourimage.jpg" alt="describe this image"/></a>

Image Link Opens In New Window

<a href="http://www.yourlink.com" target="_blank"><img src="http://www.yoursite.com/yourimage.jpg" alt="describe this image"/></a>

Image Width and Height

You can change the width and height of the image if you need to, however it’s usually best to resize your image prior to adding it to your site. You can specify the width and height below for browser compatibility. Change the width and height values to those of your actual image:
<img src="http://www.yoursite.com/yourimage.jpg" alt="describe this image" width="450" height="600"/>

Align Image to Left or Right of Paragraph

If you want to place your image to the left or right of a paragraph, use the following code, replacing “left” with “right” if you like:
<img src="http://www.yoursite.com/yourimage.jpg" alt="describe this image" align="left"/>

Backgrounds

The following should be completed in your site’s main CSS file, or a dedicated CSS section of your website/blog editor. If you don’t have a CSS section or file, you can place these codes in between <style> and </style> tags in the <head> section of your website’s HTML, although it is recommended to have an external CSS file.

Page Background Color

Change the overall background of your website or blog with this code. Replace the color hex code with your own.
body {
background-color:#c3c3c3;
}

Repeating Background Image

For smaller backgrounds that you want tiled, or larger backgrounds that were made to be repeating, use this code and replace the image URL with your own. You will need to upload the image online first:
body {
background-image:url(http://www.yourwebsite.com/background-image.jpg); 
background-repeat:repeat;
}
Change the above red “repeat” if you want the image to only repeat vertically: repeat-y
Change the above red “repeat” if you want the image to only repeat horizontally: repeat-x

Non-Repeating Background Image

For background images that you want displayed only once (not repeated or tiled). Replace the image URL with your own.
body {
background-image:url(http://www.yourwebsite.com/background-image.jpg);
background-repeat:no-repeat;
}

Top Centered Non-Repeating Background Image

Center your background image on the page, at the top. Replace the image URL with your own.
body {
background-image:url(http://www.yourwebsite.com/background-image.jpg);
background-repeat:no-repeat;
background-position: top center;
}

Top Centered Vertical Repeating Background Image

Center your background image on the page, at the top. It will repeat vertically down the page. Replace the image URL with your own.
body {
background-image:url(http://www.yourwebsite.com/background-image.jpg);
background-repeat:repeat-y;
background-position: top center;
}

Lists

Ordered List

This will create a numbered list. Replace list elements with your own:
<ol>
<li>List item 1</li>
<li>List item 2</li>
<li>List item 3</li>
</ol>

Unordered List With Bullets

This will create a list with bullets instead of numbers. Replace list elements with your own:
<ul>
<li>List item 1</li>
<li>List item 2</li>
<li>List item 3</li>
</ul>

Unordered List With Different Bullet Types

You can change the bullet type of any unordered list to circle, square, or disc (default):
<ul>
<li style="list-style-type:square">List item 1</li>
</ul>

Unordered List with Custom Image Bullet

If you want to use your own bullet image instead of the default ones, you can do that as well with a little CSS. Perhaps a star or a heart or check mark? You will need to create a small enough image and upload it somewhere online:
<ul style="list-style-image:url('http://yourimageurl.com/yourbullet.jpg')">
 <li>List item 1</li>
 <li>List item 2</li>
 <li>List item 3</li>
 </ul>

Special HTML Characters

Copyright symbol ©
&copy;
Less Than Symbol <
&lt;
Greater Than Symbol >
&gt;
Ampersand &
&amp;
Trademark Symbol ™
&trade;
Non-breaking Space
&nbsp;
Quotation Mark ”
&quot;
Registered Trademark ®
&reg;
Heart ♥
&hearts;
Euro sign €
&euro;
Left Arrow ←
&larr;
Right Arrow →
&rarr;
Up Arrow ↑
&uarr;
Down Arrow ↓
&darr;
Spade ♠
&spades;
Club ♣
&clubs;
Diamond ♦
&diams;