Posts Tagged 'CSS'

November 6, 2014

#T4 -Tips and Tricks - Pure CSS Sticky Footers

Who doesn’t like a walk down memory lane? In our #T4 series, SoftLayer brings back popular tech tip blog posts. #ThrowbackThursday #T4 #ThrowbackThursdayTechTips

Sticky footers are still landing developers in, well, sticky situations. Don’t fret—we’ve all been there. We’re bumping our popular Tips and Tricks – Pure CSS Sticky Footers blog post that was originally posted two years ago today!

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. We got a LOT of feedback the first time this blog was posted, a lot of you loved it, and some of you brought to my attention that some browser environments didn’t support this method.

For this throwback, I have modified the code (the HTML and the CSS), but as you can see, not by too much, only a few things have changed. This method uses the: after attribute, which in my opinion is a LOT cooler. This should help those of you who could not get the previous method to work as this utilizes more of a modern technique and has a lot more universal compatibility!

So enjoy!

Go from this:

CSS Footer

To this:

CSS Footer

  1. Start by getting the HTML structure in place first:
    <div id="page">
     
          <div id="header"> </div>
     
          <div id="main"> </div>
    </div> <!-- /page -->
     
    <div id="footer"> </div>
  2. Then code the CSS for the full page:
    * {
          margin: 0;
     
    html, body {
     
          height: 100%;
    }
  3. Code the rest as:
    #page {
          min-height: 100%;
          margin-bottom: -100px; /* equal to the fixed height of your footer */
    }
     
    #page:after {
          content: “”;
          display:block;
    }
     
     
    #footer, #page:after {
          height: 100px;
    }
  4. 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;
    }

To read my FAVORITE perk of this trick: check out the original post here.

For questions, comments, or just feel like chatting, contact us at social@softlayer.com.

-Cassandra

October 23, 2014

CSS3 Tips and Tricks – Mastering Multiple Backgrounds

I’ve written a lot of blog posts, some on our very own SoftLayer Development Network, but most of them have been posted right here on SoftLayer’s main blog. One of the most popular is a tutorial I wrote on being able to create a customized background depending on the user’s location. For example: A person visiting a website from the United States during the daytime may see a beautiful yellow background with an orange glow and a bright yellow sun just above the horizon, while a surfer from China may see the same website, but with a dark purple background with subtle white stars and a shimmering moon because it is night. The example I wrote customized the CSS to the time zone based on locale tailoring the site with a more personal touch.

The demand for sites to serve a more interactive experience has always been large in volume, but few websites actually deliver.

Luckily, our Web languages are evolving all of the time, and since I’ve written the “What time is it for you?” blog on our SLDN, more advancements have been made to the background functionality and browser compatibility. This means MORE browsers support these new features, and it’s compliant across the board!

Let’s start off with our usual HTML document (with an addition of an empty div for now, this is where we’re going to master our background techniques).

<html>
<head>
    <title>CSS3 Tips and Tricks – Mastering Multiple Backgrounds</title>
</head>
<body>
    <div class=”slBackgrounds”></div>
</body>
</html>

With CSS3, we can define multiple backgrounds in one declaration, like this:

background: url('earth.png') no-repeat top 30px center, url('star_bg.png') repeat-y center;

By separating each background with just a comma, we’re able to declare many backgrounds for one div. Let’s go ahead and add our multi-background CSS in the <head> of our document:

<style>
    .slBackgrounds {
        width: 300px;
        height: 300px;
        margin: 0 auto;
        background: url('earth.png') no-repeat top 30px center, url('star_bg.png') repeat-y center;
        transition:background-position 600s;
    }
 
    .slBackgrounds:hover {
        background-position: top 30px center, 0px 60000px;
    }
</style>

After adding the CSS styling, you should have something that looks similar to the following:

You’ll notice I added a transition property to the .slBackgrounds class, and I bet you’re wondering why? Everybody has their own learning technique that helps them absorb concepts better and faster than other methods. My learning method (and probably 75 percent of other developers) happens to be the challenge technique: When I learn something new, I think about something extremely fun and challenging that I would like to do with this newfound knowledge beyond just the base use. For instance, why learn how to use multiple backgrounds with CSS3 and just have a five-line blog when we can learn to use multiple backgrounds, AND create an awesome animation sequence that can jazz up the old and boring background system?

Not only does this jazz it up, but by using additions such as the transition and :hover properties, we’re able to open new doors to possibilities with interactivity.

If you haven’t guessed already, the .slBackgrounds:hover section covers what should happen to the .slBackgrounds div when the user hovers over it; in this case, there’s a background-position declaration. The ‘top 30px center’ applies to the first background image, and the ‘0px 60000px’ applies to the second (gotta love multiple backgrounds!).

Go ahead and hover over our images! You should see something like this:

Something pretty simple, but I bet you can already think of a hundred things you can do with the CSS3 multiple background ability, huh? The great news is that the cross-browser compatibility is awesome and supports all newer browsers and most reasonably older ones too! And to think . . . barely five or six years ago it took MUCH more innovative coding and workarounds to achieve results like this without just embedding a flash file or an animated gif!

We’d love to hear how YOU’RE using multiple backgrounds!

- Cassandra

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.

Subscribe to css