Showing posts with label css. Show all posts
Showing posts with label css. Show all posts

Saturday, February 12, 2011

How To Create Mega Drop Down Menus CSS & j Query For Web site

Step 1. Foundation – HTML :
Just like all of my navigation tutorials, start by creating an unordered list. Since we will be using CSS Sprites for our navigation states, each link within the list item should have a unique class name to it.
<ul id="topnav">
    <li><a href="#" class="home">Home</a></li>
    <li><a href="#" class="products">Products</a></li>
    <li><a href="#" class="sale">Sale</a></li>
    <li><a href="#" class="community">Community</a></li>
    <li><a href="#" class="store">Store Locator</a></li>
</ul>
Step 2. Styling Foundation – CSS
Since our drop down menu will be using absolute positioning, be sure to add a relative positioning to the list item. Shoot the text off of the page by specifying a text-indent of -9999px. We will then replace each navigation link with an image by specifying an image path to each link class name.

ul#topnav {
margin: 0; padding: 0;
float:left;
width: 100%;
list-style: none;
font-size: 1.1em;
}
ul#topnav li {
float: left;
margin: 0; padding: 0;
position: relative; /*--Important--*/
}
ul#topnav li a {
float: left;
text-indent: -9999px; /*--Push text off of page--*/
height: 44px;
}
ul#topnav li:hover a, ul#topnav li a:hover { background-position: left bottom; } /*--Hover State--*/
ul#topnav a.home {
background: url(nav_home.png) no-repeat;
width: 78px;
}
ul#topnav a.products {
background: url(nav_products.png) no-repeat;
width: 117px;
}
ul#topnav a.sale {
background: url(nav_sale.png) no-repeat;
width: 124px;
}
ul#topnav a.community {
background: url(nav_community.png) no-repeat;
width: 124px;
}
ul#topnav a.store {
background: url(nav_store.png) no-repeat;
width: 141px;
}
Step 3. Creating the Mega Sub Navigation – HTML
Add a class of “sub” right after your main navigation link and nest unordered lists within. Each nested unordered list will act as the nav columns of your mega drop down.

<ul id="topnav">
    <li><a href="#" class="home">Home</a></li>
    <li>
     <a href="#" class="products">Products</a>
        <div class="sub">
            <ul>
                <li><h2><a href="#">Desktop</a></h2></li>
                <li><a href="#">Navigation Link</a></li>
                <li><a href="#">Navigation Link</a></li>
            </ul>
            <ul>
                <li><h2><a href="#">Laptop</a></h2></li>
                <li><a href="#">Navigation Link</a></li>
                <li><a href="#">Navigation Link</a></li>
            </ul>
            <ul>
                <li><h2><a href="#">Accessories</a></h2></li>
                <li><a href="#">Navigation Link</a></li>
                <li><a href="#">Navigation Link</a></li>
            </ul>
            <ul>
                <li><h2><a href="#">Accessories</a></h2></li>
                <li><a href="#">Navigation Link</a></li>
                <li><a href="#">Navigation Link</a></li>
            </ul>
        </div>
    </li>
    <li><a href="#" class="sale">Sale</a></li>
    <li><a href="#" class="community">Community</a></li>
    <li><a href="#" class="store">Store Locator</a></li>
</ul>
Step 4. Styling Mega Sub Navigation – CSS

To get the sub nav to stick to the bottom left corner of the parent hovered nav, be sure to set an absolute position to the .sub container with the coordinate of top 44px and left 0px. For style, I added rounded corners to those browsers that support it (Firefox/Chrome/Safari).


Keep in mind when having multiple levels of nested lists, you need to override its conflicting properties. Check out the comments below.
ul#topnav li .sub {
position: absolute; /*--Important--*/
top: 44px; left: 0;
z-index: 99999;
background: #344c00 url(sub_bg.png) repeat-x; /*--Background gradient--*/
padding: 20px 20px 20px;
float: left;
/*--Bottom right rounded corner--*/
-moz-border-radius-bottomright: 5px;
-khtml-border-radius-bottomright: 5px;
-webkit-border-bottom-right-radius: 5px;
/*--Bottom left rounded corner--*/
-moz-border-radius-bottomleft: 5px;
-khtml-border-radius-bottomleft: 5px;
-webkit-border-bottom-left-radius: 5px;
display: none; /*--Hidden for those with js turned off--*/
}
ul#topnav li .row { /*--If needed to break out into rows--*/
clear: both;
float: left;
width: 100%;
margin-bottom: 10px;
}
ul#topnav li .sub ul{
list-style: none;
margin: 0; padding: 0;
width: 150px;
float: left;
}
ul#topnav .sub ul li {
width: 100%; /*--Override parent list item--*/
color: #fff;
}
ul#topnav .sub ul li h2 { /*--Sub nav heading style--*/
padding: 0;  margin: 0;
font-size: 1.3em;
font-weight: normal;
}
ul#topnav .sub ul li h2 a { /*--Sub nav heading link style--*/
padding: 5px 0;
background-image: none;
color: #e8e000;
}
ul#topnav .sub ul li a {
float: none;
text-indent: 0; /*--Override text-indent from parent list item--*/
height: auto; /*--Override height from parent list item--*/
background: url(navlist_arrow.png) no-repeat 5px 12px;
padding: 7px 5px 7px 15px;
display: block;
text-decoration: none;
color: #fff;
}
ul#topnav .sub ul li a:hover {
color: #ddd;
background-position: 5px 12px ;/*--Override background position--*/
}

Step 5. Setting up jQuery & Hover Intent

For those who are not familiar with jQuery, do check out their site first and get an overview of how it works. I’ve shared a few tricks that I have picked up along the way, you can check those out as well.
Initial Step – Call the jQuery file
You can choose to download the file from the jQuery site, or you can use this one hosted on Google.

script type="text/javascript"
src="http://ajax.googleapis.com/ajax/libs/jquery/1.3/jquery.min.js"></script>
After calling the jQuery file, visit and download the latest Hover Intent jQuery Plugin. Save the file to your current directory, and call the file.
<script type="text/javascript" src="jquery.hoverIntent.minified.js"></script>

Step 6. Launching Code on Document Ready
Directly after the line where you called your jQuery and hover intent file, start a new <script> tag and start your code by using the $(document).ready event. This allows your jQuery code to run the instant the DOM is ready to be manipulated. The code you will be writing in the next few steps will all take place within.

$(document).ready(function() {
//Code goes here
});



Step 7. Set Hover Over & Hover Out Events – jQuery

Note: When using the hover intent plugin, it requires each hover over and hover out state to be in its own function.


The Logic


When a drop down parent link is hovered over:


Find .sub and fade it in (By default, we will fade the opacity down to 0)
Check if a .row exists (in case you want more than one row in the drop down)
If .row does exists, find the widest row and set the width of the .sub container.
If .row does not exist, set the width of the .sub container.
On hover out:


Find .sub and fade it out (Opacity 0)
Hide .sub (Display none – so it is completely out of the way)
The following script contains comments explaining which jQuery actions are being performed.

//On Hover Over
function megaHoverOver(){
    $(this).find(".sub").stop().fadeTo('fast', 1).show(); //Find sub and fade it in
    (function($) {
        //Function to calculate total width of all ul's
        jQuery.fn.calcSubWidth = function() {
            rowWidth = 0;
            //Calculate row
            $(this).find("ul").each(function() { //for each ul...
                rowWidth += $(this).width(); //Add each ul's width together
            });
        };
    })(jQuery); 


    if ( $(this).find(".row").length > 0 ) { //If row exists...


        var biggestRow = 0;


        $(this).find(".row").each(function() { //for each row...
            $(this).calcSubWidth(); //Call function to calculate width of all ul's
            //Find biggest row
            if(rowWidth > biggestRow) {
                biggestRow = rowWidth;
            }
        });


        $(this).find(".sub").css({'width' :biggestRow}); //Set width
        $(this).find(".row:last").css({'margin':'0'});  //Kill last row's margin


    } else { //If row does not exist...


        $(this).calcSubWidth();  //Call function to calculate width of all ul's
        $(this).find(".sub").css({'width' : rowWidth}); //Set Width


    }
}
//On Hover Out
function megaHoverOut(){
  $(this).find(".sub").stop().fadeTo('fast', 0, function() { //Fade to 0 opactiy
      $(this).hide();  //after fading, hide it
  });
}

Step 8. Set Custom Configurations & Trigger Function

Now that we declared the hover over and hover out function in the above step, its now time to set the custom configurations and call the hover intent function.

//Set custom configurations
var config = {
     sensitivity: 2, // number = sensitivity threshold (must be 1 or higher)
     interval: 100, // number = milliseconds for onMouseOver polling interval
     over: megaHoverOver, // function = onMouseOver callback (REQUIRED)
     timeout: 500, // number = milliseconds delay before onMouseOut
     out: megaHoverOut // function = onMouseOut callback (REQUIRED)
};


$("ul#topnav li .sub").css({'opacity':'0'}); //Fade sub nav to 0 opacity on default
$("ul#topnav li").hoverIntent(config); //Trigger Hover intent with custom configurations

For more detailed explanation of how hover intent works, check out their website.
Conclusion
Keep in mind that this script calculates the width of your .sub container (adding up all UL’s per row) and automatically adjusts it. If you would like to specify your own custom width, you can delete that portion of the code and specify a static width in your CSS. This all depends on what you are trying to add in your mega drop down, and each scenario may be different. I hope you grasped the basic concepts of this tutorial so you can make your own custom mega drop down for future projects. If you have any questions, concerns, or suggestions, please let me know!                      












Thursday, February 10, 2011

CSS Sprites: What They Are and How to Use Them ?

CSS Sprites :

A visually appealing website must have a great design. And usually with a great design, comes great images. And with great images, comes loading time. And with loading time, comes slow pages. ect, ect. Images are key in most web designs, so it’s always important to keep in mind how to optimize your images for the best user experience.
There are countless methods on minimizing the load time on your site, but this post will address one way in particular: sprites. More specifically, CSS sprites.


The use of CSS sprites is a fairly common practice with web designers. But what are they? The name may be a little misleading, as CSS sprites aren’t small, but big images containing dozens, and even hundreds, of little images. 
History :
Super Mario Bros. Sprites
Sprites originated in video games, back during the 8-bit glory days. Every visual item in a game was drawn as an individual image that would later be ‘layered‘ into the game as it was being played. However, as the complexity of games increased, game developers realized the benefits from combining all the images for a game into a singe sprite. By combining all the images into a single sprite (in a grid like formation), they could program the game to map positions of each individual graphic, and selectively placed them into the game.


What does this have to do with web development? Well, aren’t websites not unlike 8-bit games? Eh?
Why Sprites?
Sprite image from Google

Having all these images individually makes for smaller files sizes and fast loading, right? You may think so, but no. While it may look like your page loads fast, since there are dozens of images half loaded, they’re actually loading slower.


For each image, an HTTP-Request is called to download the image, and having a few dozen of them called at the same time slows down the entire process. Not to mention that despite a single image being smaller than a large sprite, file sizes add up, and fast. Combining a bunch of your images into a single sprite cuts down of your HTTP-requests, lowers the total file size, and your page then loads faster.

Example :

While the individual images on their own are smaller in size, collectively they’re more than 5x larger than the single sprite image.


Another great benefit to using sprites is when you use images for the :hover state. Normally, you’d have to use JavaScript to pre-load an image used in a :hover state, but if you’re using a sprite, and simply change the background position on :hover, there is no need to pre-load the image, since it will already be loaded. 



Share