Posts Tagged 'CSS'

September 16, 2014

CSS3 Tips and Tricks – Generated Content Without jQuery

If you guys have read any of my past blogs, you know how much I LOVE jQuery, but every good developer knows that if there’s an easier or more efficient way of doing something: DO IT. With all the new developments with CSS3, HTML5, etc. etc., sometimes we have to get back to basics to relearn how to do things more efficiently, so here it goes!

Nearly every website has some form of 2.0/dynamic/generated content nowadays, and if your site doesn’t… well, it probably should catch up! I’ll show you how with some new CSS tricks and how it can reduce a lot of overhead of including the entire jQuery library (which would save you approximately 84kb per page load, assuming you have no other asynchronous/client side functionality you need).

I’ll start off with an easy example, since I know most of you take these examples and let your creativity run wild for your own projects. (Note to self: start a “Code Gone Wild” series.)

Usually this is the part where I say “First, let’s include the jQuery library as always.” Not this time, let’s break the rules!

FIRST, start off your document like any other (with the basic structure, set your DOCTYPE appropriately, i.e. strict vs transitional):

<!DOCTYPE html>
<html>
<head>
</head>
<body>
</body>
</html>

Wow, you can already tell this generated content’s going to be a TON easier than using jQuery (for those of you whom aren’t already jQuery fans).

Now let’s add in a div there; every time we hover over that div, we’re going to display our generated content with CSS. Inside of our div, we’re going to place a simple span, like so:

<!DOCTYPE html>
<html>
<head>
</head>
<body>
     <div class=”slisawesome”>
          <span data-title="Hello Cassandra!">What’s my name?</span>
     </div>
</body>
</html>

As you can see, the span content contains a simple question and the data-title attribute contains the answer to that question.

Now let’s just make this div a little bit prettier before we get into the fancy stuff.

Add some style to the <head> section of our document:

<style>
     .slisawesome  {
          /* Will TOTALLY be making another blog about the cool CSS gradients soon */
          background:linear-gradient(to bottom, #8dd2d9 , #58c0c7);
          padding: 20px;  /* give the box some room to breathe */
          width: 125px;  /* give it a fixed width since we know how wide it should be  */
          margin: 100px auto;  /* move it away from the top of the screen AND center it */
          border: 1px solid black;  /* this is just a little border */
          position: relative;  /* this is to help with our generated content positioning */
     }
</style>

Now you should have something that looks like this:

This is good; this is what you should have. Now let’s make the magic happen and add the rest of our CSS3:

<style>
     .slisawesome  {
          /* Will TOTALLY be making another blog about the cool CSS gradients soon */
          background:linear-gradient(to bottom, #8dd2d9 , #58c0c7);
          padding: 20px;  /* give the box some room to breathe */
          width: 125px;  /* give it a fixed width since we know how wide it should be  */
          margin: 100px auto;  /* move it away from the top of the screen AND center it */
          border: 1px solid black;  /* this is just a little border */
          position: relative;  /* this is to help with our generated content positioning */
     }
     .slisawesome span::before {
          content:attr(data-title); /* assigning the data-title attribute value to the content */
          opacity: 0; /* hiding data-title until we hover over it */
          position: absolute; /* positioning our data-title content */
          margin-top: 50px; /* putting more space between our question and answer */
 
          /* Fancy transitions for our data-title when we hover over our question */
          /* which I’m TOTALLY going to write another blog for ;) If you guys want, of course */
          -webkit-transition:opacity 0.4s; /* determines the speed of the transition */
          transition:opacity 0.4s; /* determines the speed of the transition */
     }
</style>

Now, right now, your page should still look like this:

That’s okay! We still have ONE more step to go:

<style>
     .slisawesome  {
          /* Will TOTALLY be making another blog about the cool CSS gradients soon */
          background:linear-gradient(to bottom, #8dd2d9 , #58c0c7);
          padding: 20px;  /* give the box some room to breathe */
          width: 125px;  /* give it a fixed width since we know how wide it should be  */
          margin: 100px auto;  /* move it away from the top of the screen AND center it */
          border: 1px solid black;  /* this is just a little border */
          position: relative;  /* this is to help with our generated content positioning */
     }
     .slisawesome span::before {
          content:attr(data-title); /* assigning the data-title attribute value to the content */
          opacity: 0; /* hiding data-title until we hover over it */
          position: absolute; /* positioning our data-title content */
          margin-top: 50px; /* putting more space between our question and answer */
 
          /* Fancy transitions for our data-title when we hover over our question */
          /* which I’m TOTALLY going to write another blog for ;) If you guys want, of course */
          -webkit-transition:opacity 0.4s; /* determines the speed of the transition */
          transition:opacity 0.4s; /* determines the speed of the transition */
     }
     /* Drum Roll --------- Here’s our hover magic */
     .slisawesome span:hover::before{
          opacity:1;
     }
     /* Okay… that was a little anticlimactic… losing cool points */
</style>

Despite my anticlimactic adding of “the magic,” we just added a :hover that will show full opacity when we hover, so refresh your page and try it out! You should see something like this when you hover over THE QUESTION:

Of course you could REALLY start getting fancy with this by adding some php variables for the logged in user, or perhaps make it dynamic to location, time, etc. The possibilities are endless, so go… go and expand on this awesome generated content technique!

-Cassandra

November 6, 2012

Tips and Tricks - Pure CSS Sticky Footers

By now, if you've seen my other blog posts, you know that I'm fascinated with how much JavaScript has evolved and how much you can do with jQuery these days. I'm an advocate of working smarter, not harder, and that maxim knows no coding language limits. In this post, I want to share a pure CSS solution that allows for "sticky" footers on a web page. In comparing several different techniques to present this functionality, I found that all of the other routes were overkill when it came to processing time and resource usage.

Our objective is simple: Make the footer of our web page stay at the bottom even if the page's content area is shorter than the user's browser window.

This, by far, is one of my *favorite* things to do. It makes the web layout so much more appealing and creates a very professional feel. I ended up kicking myself the very first time I tried to add this functionality to a project early in my career (ten years ago ... already!?) when I found out just how easy it was. I take solace in knowing that I'm not alone, though ... A quick search for "footer stick bottom" still yields quite a few results from fellow developers who are wrestling with the same frustrating experience I did. If you're in that boat, fear no more! We're going to your footers in shape in a snap.

Here's a diagram of the problem:

CSS Footer

Unfortunately, a lot of people try to handle it with setting a fixed height to the content which would push the footer down. This may work when YOU view it, but there are several different browser window heights, resolutions and variables that make this an *extremely* unreliable solution (notice the emphasis on the word "extremely" ... this basically means "don't do it").

We need a dynamic solution that is able to adapt on the fly to the height of a user's browser window regardless if the resize it, have Firebug open, use a unique resolution or just have a really, really weird browser!

Let's take a look at what the end results should look like:

CSS Footer

To make this happen, let's get our HTML structure in place first:

<div id="page">
 
      <div id="header"> </div>
 
      <div id="main"> </div>
 
      <div id="footer"> </div>
 
</div>

It's pretty simple so far ... Just a skeleton of a web page. The page div contains ALL elements and is immediately below the

tags in the page code hierarchy. The header div is going to be our top content, the main div will include all of our content, and the footer div is all of our copyrights and footer links.

Let's start by coding the CSS for the full page:

Html, body {
      Padding: 0;
      Margin: 0;
      Height: 100%;
}

Adding a 100% height allows us to set the height of the main div later. The height of a div can only be as tall as the parent element encasing it. Now let's see how the rest of our ids are styled:

#page {
      Min-height: 100%;
      position:relative;
}
 
#main {
      Padding-bottom: 75px;   /* This value is the height of your footer */
}
 
#footer {
      Position: absolute;
      Width: 100%;
      Bottom: 0;
      Height: 75px;  /* This value is the height of your footer */
}

These rules position the footer "absolutely" at the bottom of the page, and because we set #page to min-height: 100%, it ensures that #main is exactly the height of the browser's viewing space. One of the best things about this little trick is that it's compliant with all major current browsers — including Firefox, Chrome, Safari *AND* Internet Explorer (after a little tweak). For Internet Explorer to not throw a fit, we need concede that IE doesn't recognize min-height as a valid property, so we have to add Height: 100%; to #page:

#page {
      Min-height: 100%;  /* for all other browsers */
      height: 100%;  /* for IE */
      position:relative;
}

If the user does not have a modern, popular browser, it's still okay! Though their old browser won't detect the magic we've done here, it'll fail gracefully, and the footer will be positioned directly under the content, as it would have been without our little CSS trick.

I can't finish this blog without mentioning my FAVORITE perk of this trick: Should you not have a specially designed mobile version of your site, this trick even works on smart phones!

-Cassandra

September 6, 2012

Tips and Tricks - jQuery equalHeights Plugin

Last month, I posted a blog about dynamically resizing divs with jQuery, and we received a lot of positive feedback about it. My quest to avoid iframes proved to be helpful, so I thought I'd share a few more esoteric jQuery tips and tricks that may be of use to the developers and designers in the audience. As I thought back about other challenges I've faced as a coder, a great example came to mind: Making divs equal height, regardless of the amount of content inside.

I haven't seen many elegant div-based solutions for that relatively simple (and common) task, so I've noticed that many people struggle with it. Often, developers will turn back to the "Dark Side" of using tables to format the content since all columns would have the same height as the tallest column by default:

JQuery Tutorial

It was easy theme table columns and to achieve the coveted 100% height that many designers seek, but emulating that functionality with divs proves to be much more difficult. A div is like the Superman of HTML elements (faster-loading, more flexible, more dynamic, etc.), and while it has super powers, it also has its own Kryptonite-like weaknesses ... The one relevant to this blog post being that floating three div elements next to each other isn't going to give you the look of a table:

JQuery Tutorial

Each of the three divs has its own height, so if you're doing something as simple as applying background colors, you're going to wind up with an aesthetically unpleasing result: It's going to look funky.

You could get into some nifty HTML/CSS workarounds, but many frustrated theme creators and designers will tell you that if your parent elements don't have a height of a 100%, you're just wasting coding lines. Some complex solutions create the illusion of all three divs being the same height (which is arguably better than setting fixed heights), but that complexity can be difficult to scale and repeat if you need to perform similar tasks throughout your site or your application. The easiest way to get the functionality you want and the simplicity you need: The jQuery equalHeights plugin!

With a few class declarations in your existing HTML, you get the results you want, and with equalHeights, you can also specify the minimum and maximum parameters so it will create scrollable divs if the tallest element happens to be higher than your specified maximum.

How to Use jQuery equalHeights

First and foremost, include your JQuery lirbraries in the <HEAD> of your document:

<script src="//ajax.googleapis.com/ajax/libs/jquery/1.8.0/jquery.min.js"></script>
<script language="javascript" type="text/javascript" src="jquery.equalheights.js"></script>

The equalHeights plugin is not a hosted library, so you have to host the file on your server (here's the link again).

With the required libraries called in our document, it's time to make the magic happen in your HTML.

Create Your Divs

<div class="divHeight">This DIV is medium sized, not too big and not too small, but just right.</div>
<div class="divHeight">This DIV has a lot of useful content and media that the user can interact with, thus it's very tall.</div>
<div class="divHeight">This DIV is tiny. Period.</div>

To have them line up next to each other, you'd have them float:left; in your CSS, and now you need to apply the equalHeights function.

Call the equalHeights Plugin
In order for the script to recognize the height of the tallest element, you'd need to call $(document).ready just before the </body> tag on your page. This will ensure that the page loads before the function runs.

The call looks like this:

<script type="text/javascript">$(document).ready(function() {
$(".divHeight").equalHeights();
});</script>

If you want to specify a minimum and maximum (i.e. The div should be at least this tall and should be no taller than [adds scrollbar if the div size exceeds] the maximum), just add the parameters:

<script type="text/javascript">$(document).ready(function() {
$(".divHeight").equalHeights(300, 600);
});</script>

The initial call does not change the appearance of the divs, but the time it takes to do the resizing is so miniscule that users will never notice. After that call is made and the height is returned, each div with the class of divHeight will inherit the the same height, and your divs will be nice and pretty:

JQuery Tutorial

This trick saved me a lot of headache and frustration, so hopefully it will do the same for you too!

-Cassandra

August 8, 2012

No iFrames! Dynamically Resize Divs with jQuery.

It's no secret that iframes are one of the most hated methods of web page layouts in the web development world — they are horrible for SEO, user experience and (usually) design. I was recently charged with creating a page that needed functionality similar to what iframes would normally provide, and I thought I'd share the non-iframe way I went about completing that project.

Before I get into the nitty-gritty of the project, I should probably unpack a few of the reasons why iframes are shunned. When a search engine indexes a page with iframes, each iframe is accurately recorded as a separate page — iframes embed the content of one we page inside of another, so it makes sense. Because each of those "pages" is represented in a single layout, if a user wanted to bookmark your site, they'd probably have a frustrating experience when they try to return to your site, only to find that they are sent directly to the content in one of the frames instead of seeing the entire layout. Most often, I see when when someone has a navigation bar in one frame and the main content in the other ... The user will bookmark the content frame, and when they return to the site, they have no way to navigate the pages. So what's a developer to do?

The project I was tasked with required the ability to resize only certain sections of a page, while asynchronously shrinking another section so that the entire page would always stay the same size, with only the two sections inside changing size.

Let's look at an example with two divs, side by side on a web page:

iFrame Tutorial

One div will contain a navigation menu to jump to different pages of the website (#sidebar), and the second div will contain all the content for that page (#content). If some of the elements in #sidebar are too long to read with the default width of the div, we want to let the user freely resize the two divs without changing the width of the page.

Our task is straightforward: When #sidebar expands in width, also expand the navigation and shrink #content along with the main content inside #content. If #sidebar shrinks, the navigation, #content and main content would respond accordingly as well:

iFrame Tutorial

It's a relatively easy concept to do with iFrames ... But then you remember that iframes are no longer cool (yes, there was a time long ago when iframes were cool). I decided to turn to my favorite alternative — jQuery — and the fix was actually a lot easier than I expected, and it worked beautifully. Let's run through a step-by-step tutorial.

1. HTML

Lay out your two divs:

<div id="sidebar"> 
<div class="sidebar-menu">
<!-- all your sidebar/navigational items go here -->
</div>
</div>
<div id="content">
<!-- all your main content goes here -->
</div>

2. CSS

Style your divs:

#sidebar {
       width: 49%;
}
#content {
width: 49%;
        float: left;
}

3. jQuery

Now that we have our two divs side by side, let's apply some jQuery magic. To do that, Let's include our jQuery files in the <HEAD> of our document:

<link href="http://ajax.googleapis.com/ajax/libs/jqueryui/1.8/themes/base/jquery-ui.css" rel="stylesheet" type="text/css"/>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.5/jquery.min.js"></script>
<script src="http://ajax.googleapis.com/ajax/libs/jqueryui/1.8/jquery-ui.min.js"></script>

Now that we have the necessary scripts, we can write our function:

<script type="text/javascript">
  $(document).ready(function() {
    $( "#sidebar" ).resizable({      
    });
    $("#sidebar ").bind("resize", function (event, ui) {
            var setWidth = $("#sidebar").width();
            $('#content).width(1224-setWidth);
            $('.menu).width(setWidth-6);
        });
  });
</script>

I know that might seem like an intimidating amount of information, so let's break it down:

   $( "#sidebar" ).resizable({      
   });

This portion simply makes the div with the ID of "sidebar" resizable (which accomplishes 33% of what we want it to do).

   $("#sidebar ").bind("resize", function (event, ui) {

By using the .bind, we are able to trigger other events when #sidebar is called.

            var setWidth = $("#sidebar").width();
            $('#content).width(1224-setWidth);

This is where the magic happens. We're grabbing the current width of #sidebar and subtracting it from the width you want your site to be. This code is what keeps your page stays the same width with only the divs changing sizes.

            $('.menu).width(setWidth-6);

This part of the code that expands the contents in the navigation along with #sidebar.

You can see a working example of iframe-like functionality with jQuery here: http://jqueryui.com/demos/resizable/

The only part you won't find there is the trick to adjust a corresponding div's size to make it grow/shrink with the first ... I had a heck of a time searching that on the web, so hopefully this quick tutorial will help other developers who might be searching for this kind of functionality!

- Cassandra

June 5, 2012

New SoftLayer.com Design: Build the Future

If you've been reading the SoftLayer Blog via an RSS feed or if you find yourself navigating directly to the portal to manage your SoftLayer account, you might not have noticed that the our main website has been updated again — and in dramatic fashion. Last fall we gave the site a slight refresh ... This time, we did a total rework.

We took the site in a new visual direction, with graphics and messaging to complement our mantra of customers using our platform to create their vision — to build the future.

SoftLayer Homepage

The new look — referred to as "SoftLayer at Night" by my fellow SoftLayer developer friend, Seth Thornberry — was designed to reflect our core identity, and it retires the faithful red, white and grey theme that has served us well for more than three years. The new style has received rave reviews from customers, partners and employees, and even if there has been some criticism — everyone has an opinion nowadays — we can generally chalk it up to people simply not liking change.

Highlights of the Redesign:

  • A dramatic new home page design, including visually rich "hero images" (where you see "The InnerLayer" heading if you're reading this on the SoftLayer Blog)
    SoftLayer Homepage Hero Image
  • Expanded main navigation menus at the top of each page
    SoftLayer Homepage Top Nav
  • A new lower-order navigation system on the left of all content pages
  • SoftLayer Homepage Side Nav

  • [For typographically inclined] The new design also leverages web fonts functionality to incorporate "Benton Sans," the corporate font used in print, interactive and other marketing communications.
    SoftLayer Homepage Side Nav

The new design was executed in-house, and our workflow was pretty traditional ... We like to roll up our sleeves. Page templates were created as PSD files and then hand-coded in HTML, PHP, JavaScript and CSS on top of the same framework we use for the SoftLayer Customer Portal.

During the development process, we used our new GIT code repository to facilitate the merging of all of our code onto our staging server. Since it was our first time to use GIT in a major way, there was a bit of a learning curve. The first few merges had to be reworked after finding a few errors in commit messages, but after we got a little practice, the subsequent merges went off without a hitch. The final staging merge was a breeze, and given the struggles we've had with SVN in past projects, this was a huge relief.

When it came time for the design's official launch, we ran into a hiccup related to our automatic regression testing system and problems with cached CSS files, but these issues were quickly resolved, and the new-look SoftLayer.com went live.

It took a lot of hard work from (and a lot of caffeine for) a number of people to get the new site out the door, so I'd like to make sure credit goes where it's due. Our lead designer Carlos ("Los") Ruiz did a majority of the design work, and the implementation of that design fell to Dennis Dolliver (Website Developer), Charles King (SEO Manager) and me. I should also send a shout-out to the entire marketing team who jumped in to help to proof content, test pages and keep everyone sane.

What do you think of the new design? Stay tuned for more website improvements and additions!

-Brad

May 23, 2012

Web Development - JavaScript - Creating a Sticky Menu

When designing websites, I like to focus on ease of use and accessibility for the end user. While creating your site to be friendly to screen readers and text-based browsers is a must, the accessibility I'm referring to is making it easy for your audience to navigate your site and perform certain common actions. By providing an easy interface for your users, you are immediately increasing your chances that they'll return for more of your site's goodness.

Thus far in our "Web Development" blog series, we've looked at JavaScript Optimization, HTML5 Custom Data Attributes, HTML5 Web Fonts and using CSS to style the Highlight Selection. In this post, we're going to create a "sticky" menu at the top of a page. As a user scrolls down, the menu will "stick" to the top and always be visible (think of Facebook's Timeline view), allowing the user quicker access to clicking common links. With some simple HTML, CSS and JavaScript, you can have a sticky menu in no time.

Let's start with our HTML. We're going to have a simple header, menu and content section that we'll throw in our <body> tag.

<header>
    <h1>My Header</h1>
</header>
<nav id="menu">
    <ul id="menu-list">
        <li>Items</li>
    </ul>
</nav>
<div id="content">
    Some content
</div>

For brevity, I've shortened the content I show here, but the working example will have all the information. Now we can throw in some CSS to style our elements. The important part here is how the <nav> is styled.

nav#menu {
    background: #FFF;
    clear: both;
    margin: 40px 0 80px 0;
    width: 99.8%;
    z-index: 2;
}
ul#menu-list li {
    border: solid 1px blue;
    list-style-type: none;
    display: inline-block;
    margin: 0 -3px;
    padding: 4px 10px;
    width: auto;
}

We have set the menu's background to white (#FFF) and given it a z-index of 2 so that when the user scrolls, the menu will stay on top and not be see-through. We've also set the list items to be styled inline-block, but you can style your items however you desire.

Now we get to the fun part – the JavaScript. I've created a class using Mootools, but similar functionality could be achieved using your favorite JavaScript framework. Let's examine our initialize method (our constructor) in our Stickit class.

var Stickit = this.Stickit = new Class({
    initialize: function(item, options) {
        // 'item' is our nav#menu in this case
        this.item = document.id(item);
 
        // The element we're scrolling will be the window
        this.scrollTarget = document.id(options.scrollTarget || document.window);
 
        // The 'anchor' is an empty element that will always keep the same location
        // when the user scrolls. This is needed because this.item will change and
        // we cannot rely on it for accurate calculations.
        this.anchor = new Element('div').inject(this.item, 'top');
 
        // The 'filler' is an empty element that we'll use as a space filler for when
        // the 'item' is being manipulated - this will prevent the content below from
        // jumping around when we scroll.
        this.filler = new Element('div').inject(this.item, 'after');
 
        // Set the styles of our 'filler' to match the styles of the 'item'
        this.setFillerStyles();
 
        // Initialize our scroll events – see the next code section for details
        this.initEvents();
    }
});

What we're doing here is grabbing our element to stick to the top – in this case, nav#menu – and initializing our other important elements. I'll review these in the next code section.

var Stickit = this.Stickit = new Class({
    ...
    initEvents: function() {
        var that = this,
            // Grab the position of the anchor to be used for comparison during vertical scroll
            anchorOffsetY = this.anchor.getPosition().y,
            // Grab our original styles of our 'item' so that we can reset them later
            originalStyles = this.item.getStyles('margin-top', 'position', 'top');
 
        // This is the function we'll provide as our scroll event handler
        var stickit = function(e) {
            // Determine if we have scrolled beyond our threshold - in this case, our
            // anchor which is located as the first element of our 'item'
            var targetScrollY = that.scrollTarget.getScroll().y,
                fixit = targetScrollY > anchorOffsetY;
 
            if (fixit &amp;&amp; that.cache != 'fixed') {
                // If we have scrolled beyond the threshold, fix the 'item' to the top
                // of the window with the following styles: margin-top, position and top
                that.item.setStyles({
                    'margin-top': 0,
                    position: 'fixed',
                    top: 0
                });
                // Show our (empty) filler so that the content below the 'item' does not
                // jump - this would otherwise be distracting to the user
                that.filler.setStyle('display', 'block');
                // Cache our value so that we only set the styles when we need to
                that.cache = 'fixed';
            }
            else if (!fixit &amp;&amp; that.cache != 'default') {
                // We have not scrolled beyond the threshold.
                // Hide our filler
                that.filler.setStyle('display', 'none');
                // Reset the styles to our 'item'
                that.item.setStyles(originalStyles);
                // Cache our values so we don't keep resetting the styles
                that.cache = 'default';
            }
        };
 
        // Add our scroll event to the target - the 'window' in this case
        this.scrollTarget.addEvent('scroll', stickit);
        // Fire our scroll event so that all the elements and styles are initialized
        this.scrollTarget.fireEvent('scroll');
    }
});

This method contains the meat of our functionality. The logic includes that we test how far the user has scrolled down on the page. If s/he scrolls past the threshold – in this case, the anchor which is located at the very top of the "stuck" item – then we set the menu to be fixed to the top of the page by setting the CSS values for margin-top, position and top. We also display a filler so that the content below the menu doesn't jump when we set the menu's position to fixed. When the user scrolls back to the top, the styles are reset to their original values and the filler is hidden.

To see a full working example, check out this fiddle. The Stickit class I created is flexible enough so that you can "stick" any element to the top of the page, and you can specify a different scrollTarget, which will allow you to scroll another element (besides the window) and allow the item to stick to the top of that element instead of the window. If you want to give that a try, you can specify different options in Stickit and modify your CSS as needed to get it working as you'd like.

Happy coding,

-Philip

March 13, 2012

Web Development - CSS - Highlight Selection

I immediately fell in love with CSS when we were introduced in late 2000. The ability to style a whole site outside the HTML was a fantastic concept and probably my first true introduction to separation of style and content. Put your words over here, and put how you display those words over there. So simple! Since then I have always been an advocate of cascading style sheets. Today's tip will involve an effortless addition that will have your readers say, "Ooooh. That's a clever little change."

I find that when I read articles and blogs online, I not only read with my eyes, I scan the page with my mouse. Especially if it's a wordy article or not styled in smaller columns, I highlight the text by clicking and dragging to help me maintain my focus. Up until recently, whenever you selected text that way in your browser, your operating system would choose the color of the background highlight. For Windows, this is generally blue. For OS X, this is whatever you've set your preferences to (which is light blue by default).

For those of you that use a newer version of Webkit (Chrome or Safari) or Gecko (Firefox), the site designer can determine what color to highlight your selection of text, and CSS has made it easy.

/* Webkit */
::selection {
    background: #972F2C;
    color: #FFF;
}
/* Gecko/Mozilla */
::-moz-selection {
    background: #972F2C;
    color: #FFF;
}

As of today, Webkit browsers are the only ones that support ::selection without browser prefixing. Firefox requires the -moz- prefix. Here we have set the highlight background color to "SoftLayer Red" (#972F2C) and made the text color white (#FFF). It should be noted that earlier versions of Webkit and Gecko did not support anything but the background property. There is still limited support for which CSS properties are allowed during selection. You are unable to change font-style, font-size, text-decoration and many other properties, but we can hope support for most of the properties will be available in the future.

This is pretty cool so far, but we can take it one small step further. Just like other selectors, we can apply the ::selection selector to other elements and style each one differently.

h2::selection {
    background: #B72E33;
    color: #FFF;
}
p::selection {
    background: #ACEFB2;
}
div::selection {
    background: #E4DB80;
}
span::selection {
    background: #C780E4;
    color: #FFF;
}

This produces the following:

Highlighting Example

Surprise your readers and give them some highlight goodness.

Happy coding!

-Philip

January 17, 2012

Web Development - HTML5 - Web Fonts

All but gone are the days of plain, static webpages flowered with horrible repeating neon backgrounds and covered with nauseating animated GIFs created by amateur designers that would make your mother cry and induce seizures in your grandpa. Needless to say, we have come a long way since Al Gore first "created the intarwebs" in the early '90's. For those of you born in this century, that's the 1990's ... Yes, the World Wide Web is still very new. Luckily for the seven billion people on this lovely planet, many advancements have been introduced into our web browsers that make our lives as designers and developers just a little bit more tolerable.

Welcome to the third installment in Web Development series. If you're just joining us, the first posts in the series covered JavaScript Optimization and HTML5 Custom Data Attributes ... If you haven't read those yet, take a few minutes to catch up and head back to this blog where we'll be looking at how custom web fonts can add a little spice to your already-fantastic website.

If you're like me, you've probably used the same three or four fonts on most sites you've designed in the past: Arial, Courier New, Trebuchet MS and Verdana. You know that pretty much all browsers will have support for these "core" fonts, so you never ventured beyond them because you wanted the experience to remain the same for everyone, no matter what browser a user was using to surf. If you were adventurous and wanted to throw in a little typographical deviation, you might have created a custom image of the text in whatever font Photoshop would allow, but those days are in the past (or at least they should be).

Why is using an image instead of plain text unfriendly?

  1. Lack of Flexibility - Creating an image is time-consuming. Even if you have really fast fingers and know your way around Photoshop, it will never be as fast as simply typing that text into your favorite editor. Also, you can't change the styles (font-size, color, text-decoration, etc.) of an image using CSS like you can with text.
  2. Lack of Accessibility – Not everyone is alike. Some of your readers or clients may have impairments that require screen readers or a really large font. Using an image – especially one that doesn't contain a good long description – prevents those users from getting the full experience. Also, some people use text-only browsers that don't display any images. Think about your whole audience!
  3. More to Download – Plain text doesn't require the same number of bytes as an image of that same text. By not having another image, you are saving on the amount of time it takes to load your page.

Now that we're on the same page about the downsides of the "old way" of doing things, let's look at some cool HTML5-powered methods for displaying custom fonts. Before we get started, we need to have some custom fonts to use. Google has a nice interface for downloading custom fonts (http://www.google.com/webfonts), and there are plenty of other sites that provide free and non-free fonts that can suit your taste/needs. You can pick and choose which ones you'd like to use (remembering to always follow copyright guidelines), and once you've created and downloaded your collection of fonts, you'll need to setup your CSS to read them.

For simplicity, my file structure will be setup with the HTML and CSS files in the same root directory. I will have a fonts directory where I will keep all my custom fonts.

/fonts.html
/fonts.css
/styles.css
/fonts/MyCustomFont/MyCustomFont-Regular.ttf
/fonts/MyCustomFont/MyCustomFont-Bold.ttf
/fonts/...

My fonts.html file will include the two CSS files in the head section. The order in which you include the CSS files does not matter.

<link rel="stylesheet" type="text/css" href="fonts.css" />
<link rel="stylesheet" type="text/css" href="styles.css" />

The fonts.css file will include the definitions for all of our custom fonts. The styles.css file will be our main CSS file for our website. Defining our custom fonts (in fonts.css) is really simple:

@font-face {
    font-family: 'MyCustomFont';
    src: url('fonts/MyCustomFont/MyCustomFont-Regular.ttf') format('truetype');
}

It's almost too easy thanks to HTML5!

Let's break this down into its components to better understand what's going on here. The @font-face declaration will be ignored by older browsers that don't understand it, so this standards-compliant definition degrades nicely. The font-family descriptor is the name that you'll use to reference this font family in your other CSS file(s). The src descriptor contains the location of where your font is stored and the format of the font.

There are several things to note here. The quotes around MyCustomFont in the font-family descriptor are optional. If it were My Custom Font instead (in fonts.css and styles.css), it would still be successfully read. The quotes around the url portion are also optional. However, the quotes around the format portion are not optional. To keep things consistent, I have a habit of adding quotes around all of these items.

An alternative way to define the same font would be to leave off the format portion of the src descriptor. Browsers don't need the format portion if it's a standard font format (described below).

@font-face {
    font-family: 'MyCustomFont';
    src: url('fonts/MyCustomFont/MyCustomFont-Regular.ttf');
}

Like standard url inclusions in other CSS definitions, the URL item is relative to the location of the definition file (fonts.css). The URL may also be an absolute location or point to a different website altogether. If using the Google web fonts site mentioned earlier (or similar site), you may simply point the URL to the location suggested instead of downloading the actual font.

If you've dealt with web fonts before, you may already be familiar with the multiple formats: WOFF (Web Open Font Format, .woff), TrueType (.ttf), OpenType (.ttf, .otf), Embedded Open Type (.eot) and SVG Font (.svg, .svgz). I won't go into great detail here about these, but if you're interested in learning more, Google and W3C are great resources.

It should be noted that all browsers are not alike (no shock there) and some may not render some font formats correctly or at all. You can get around this by including multiple src descriptors in your @font-face declaration to try and support all the browsers.

@font-face {
    font-family: 'MyCustomFont';
    src: url('fonts/MyCustomFont/MyCustomFont-Regular.eot'); /* Old IE */
    src: url('fonts/MyCustomFont/MyCustomFont-Regular.ttf'); /* Cool browsers */
}

Now that we have our font definition setup, we have to include our new custom font in our styles.css. You've done this plenty of times:

h1, p {
    font-family: MyCustomFont, Arial;
}

There you go! For some reason if MyCustomFont is not understood, the browser will default to Arial. This degrades gracefully and is really simple to use. One thing to note is that even though your fonts.css file may define twenty custom fonts, only the fonts that are included and used in your styles.css file will be downloaded. This is very smart of the browser – it only downloads what it's going to use.

So now you have one more tool to add to your development box. As more users adopt newer, standards-compliant browsers, it's easier to give your site some spice without the headaches of creating unnecessary images. Go forth and impress your friends with your new web font knowledge!

Happy Coding!

-Philip

P.S. As a bonus, you can check out the in-line style declaration in the source of this post to see how "Happy Coding!" is coded to use the Monofett font family.

October 26, 2011

MODX: Tech Partner Spotlight

This is a guest blog from the MODX team. MODX offers an intuitive, feature-rich, open source content management platform that can easily integrate with other applications as the heart of your Customer Experience Management solution.

Company Website: http://modx.com/
Tech Partners Marketplace: http://www.softlayer.com/marketplace/modx

Free your Website with MODX CMS

Just having a website or a blog is no longer a viable online strategy for smart businesses. Today's interconnected world requires engaging customers — from the first impression, to developing leads, educating, selling, empowering customer service and beyond. This key shift in online interaction is known as Customer Experience Management, or CXM.

For businesses to have success with CXM, they need an efficient way to connect all facets of their communications and information together with a modern and consistent look and feel, and without long learning curves or frustrating user experiences. You don't want a Content Management System (CMS) that restricts your ability to meet brand standards, that lives in isolation from your other systems and data, or that fails to fulfil your businesses needs.

MODX is a content management platform that gives you the creative freedom to build custom websites limited only by your imagination. It certainly can play the central role in managing your customer experience.

Freedom from Hassle & Frustration
The most productive tools are those that simply allow you get your work done. To make life easy for content editors MODX uses familiar concepts like a hierarchical tree – similar to the folders and files on your computer. This allows content editors to relate their content to the overall website structure. But, like everything else in MODX, you aren't limited to hierarchical content and can easily employ taxonomy-, list- or category-based structures.

Similarly, editing documents should be easy. With MODX, anyone who can open a web browser and send email has the skillset to create and edit content in MODX. Most tasks are a matter of filling out simple form fields into which content is placed and is accompanied by a sensible MS Word-like editor for your main content. Furthermore, site builders and developers are able to create custom fields for custom content types and custom data allowing non-technical employees to work in an intuitive, tailored environment.

Total Creative Freedom
Your website is one of the most visible parts of your brand and you certainly don't want it limited by your CMS. MODX makes it possible to do anything that's on the modern web now — you don't have to wait for a year or hack the core to launch an HTML5 or mobile optimized site. MODX can do it all now, and even what's coming next. It outputs exactly and only what you or your site builder dictate.

MODX uses a brilliantly simple template engine that allows web designers to work with what they already know, like HTML, CSS and any JavaScript library they chose. MODX can even output things not typically associated with most content management platforms like XML, JSON or even Comma Separated Value (CSV) files that automatically download to your desktop.

Freedom to Extend
MODX provides all the requisite tools for CMS, but it also functions as a fully capable web development platform upon which you can extend functionality, employ custom applications and do just about anything you can dream up. In fact, the "X" in MODX comes from the word "extensible". Whether you want to build a Member-only website, Client Extranet, Resort Booking and Reservations system or private Social Network, you can do it on MODX.

For developers the fully-documented Object Oriented API and xPDO, MODXs database layer, provide all you need to build almost anything with MODX, even extending or overriding its core functionality. Critically, you can do all this using the API and retain a painless upgrade path without hacking the core. The MODX API architecture provides all the flexibility you or your developer might need to make MODX your own without painting your self into a corner.

Freedom from Bottlenecks
Modern web pages are made up of many component parts – site-wide headers and footers, navigation menus, articles, products and more. At some point, all these pieces need to be put together and delivered to the visitor as a single page that users expect to load quickly or they'll leave your site.

To deliver pages fast, top-performing sites use server-side caching to take all those pieces and pre-process them for fast delivery to a browser. The problem with many CMS applications is that they manually rebuild pages every single time someone visits your site. That's fine if you only have a few visitors, but your site can bog down or even fail under moderate traffic. In these circumstances, it would be disastrous if your website is featured on an industry magazine or website, national media or on a popular TV show. Your site could literally grind to a halt, costing you customers, damaging your reputation and ultimately making a bad first impression.

MODX's native page caching delivers your site quickly by default. Additionally, MODX can use high-end caching like memcache to further improve performance under load. To handle millions of pageviews daily, you need robust servers and you need to optimize your environment ... That's where scaling across multiple servers and replication with SoftLayer works perfectly with MODX.

Free Your Legacy Systems
Keeping your data, content and business information in disconnected silos is ineffective and costly. Accessing existing systems, like an Active Directory or Enterprise Content repository, makes huge difference in getting your work done headache-free. You don't have to worry about data duplication across systems, significant extra work to make everything work or synchronization issues. A new website platform should increase your productivity and enable your employees, customers and everyone else surrounding your business to find what they need and to interact efficiently and effectively.

MODX works with the tools and technology that organizations already have in place. It can easily interact with external web services or data feeds and can drive other applications via RESTful web services.

Security and Freedom to Rest Easy
Website Security is a topic that rarely surfaces during the early stages of a web project and often never comes up until your site has been compromised.

A high-quality hosting environment like those from SoftLayer are the foundation of website security. Your web CMS and its add-ons, plugin-ins or modules should not be a liability. MODX is designed with security at its core to protect your valuable website from malicious attacks. Every input is filtered, and every database query using the API eliminates the possibility of SQL injection compromises. Most importantly, the development team rigorously and continuously audits MODX to make sure its up to date and patching any new issues that may arise.

Freedom in the Community
With MODX and the MODX Community you're not alone. There are hundreds of thousands of websites built on MODX and we have a friendly, active and growing community of raving fans over 37,000 strong to whom you can look for assistance, support, education and camaraderie.

In fact, the MODX Community is one of our greatest assets.

They provide mentorship, assistance and help make MODX software better through active reporting of issues and feature requests and contributing improvements for integration by the core team.

If you're not a site builder or developer, but you want your website powered by MODX, one of the best places to start is with a MODX Solution Partner. Our network of 90+ global Solution Partners enables you to get the right-fit expertise for your project and in many cases work locally. Solution Partners are experts at MODX and know how to do things right.

Get Free
There really is a cure for the all too often restrictive, unintuitive and frustrating experience of putting content on the web. Get on the road to content management freedom with MODX. It's easy to start since MODX Revolution itself is free to download and use.

Learn more at http://modx.com/.

-Jay Gilmore, MODX

This guest blog series highlights companies in SoftLayer's Technology Partners Marketplace.
These Partners have built their businesses on the SoftLayer Platform, and we're excited for them to tell their stories. New Partners will be added to the Marketplace each month, so stay tuned for many more come.
June 28, 2011

Modern Website Design: Layout

There have been many books written about website design, and I am not about to take on the challenge of disputing any of them or trying to explain every facet of design. In this short blog, I want to explain what I have come to understand as the modern layout of websites. The term "layout" may have many different definitions, but for this article I am talking about the basic structure of your website, meaning separation of concerns, data transfer from host to client, how to handle changes in data, and when to change your page structure.

Separation of Concerns

It is important when sitting down for the first time to build a website to come up with an outline. Start by making a list of the parts of your website and the functions of those parts. I always start at the base of my web structure and work from there. HTML is always the foundation of a website; it defines the structure and outlines how you will display your data – plain and simple. It doesn't have to include data or styles, nor does it need to be dynamic ... At its essence, it's a static file that browsers can cache.

Client-side scripting languages like JavaScript will take care of client-side animations and data dispersal, while cascading style sheets (CSS) take care of style and presentation, and server-side scripting languages like PHP or Perl can take care of data retrieval and formatting.

Data Transfer

Where is your data going to come from, and what format it will be in when the client receives it? Try to use a data format that is the most compatible with your scripting languages. I use JavaScript as my primary client side scripting program, so I try to use JSON as my data format, but that's not always possible when dealing with APIs and transferring data from remote computers. JSON is quickly becoming a standard data format, but XML* is the most widely accepted format.

I prefer to use REST APIs as much as possible, because they sends the information directly on the client, rather than using the server as a proxy. However, if a REST API is not available or if there is a security risk involved, you get the advantage of being able to format the data on the server before pushing it to the client. Try to parse and format data as little as possible on the client side of things, the client should be concerned with placing data.

Changes in Data

In the past, websites were made from multiple HTML documents, each one containing different data. The structure of the pages were the same though, so the data changed, but the code was nearly identical. Later, using server side scripting programs, websites became more dynamic, displaying different data based on variables passed in the URL. Now, using AJAX or script injection, we can load new data into a static webpage without reloading. This means less redundant code, less load on the client, and better overall performance.

Page Structure

It is important when displaying data to understand when to change the structure of the page. I start by creating a structure for my home page - it needs to be very open and unrestricting so I can add pictures and text to build the site. Once the overall loose structure is established, I create a structure for displaying products (this will be more restrictive, containing tables and ordering tools). The idea is to have as few HTML structures as possible, but if you find that your data doesn't fit or if you spend a lot of time positioning your data, then it might be time to create a new structure.

The Impact of a Modern Layout

Following these steps will lead to quicker, more efficient websites. This is (of course) not a new subject, and further understanding of web layout can be found in Model-View-Controller frameworks. If you find that you spend too much time writing code to interface with databases or place data, then frameworks are for you.

-Kevin

*If you have to deal with XML, make sure to include JavaScript libraries that make it easier to parse, like JQuery.

Subscribe to css