CSS creates a three-layer separated navigation bar (Tutorial example)

Source: Internet
Author: User
Tags set cookie

The ideal goal of this navigation menu is:

1. Beautiful and personalized.

2. Clear structure, clear semantics, and no redundant labels.

3. The presentation, structure, and behavior are separated by three layers without intrusion.

4. It is conducive to data output of background programs.

5. The menu has a changed effect.

6. The menu items after clicking can be highlighted.

7. Adaptive text width. The button can change as long as the text content is changed.

8. compatible with mainstream browsers.

Let's implement this ideal menu step by step!

Many of my friends often make menus in forums, but to be honest, they are neither structured redundancy, nor tangible or expressive. What we want to build now is the best menu. Whether you are a novice or veteran, You should gain some benefits in this tutorial.

The structure of an ideal menu should be clean, non-redundant, and separated. However, for various reasons, many meaningless things will be added to it, it will be farther and farther away from "clean. Therefore, before creating a menu, some principles must be kept in mind throughout the production process and cannot be blocked by any external force.

Structure

In my impression, the ideal standard menu should have the following structure:

<Div id = "nav">

<Ul id = "menu">

<Li> <a href = "# none" Title = ""> </a> </LI>

<Li> <a href = "# none" Title = ""> community </a> </LI>

<Li> <a href = "# none" Title = "Homepage"> homepage </a> </LI>

<Li> <a href = "# none" Title = "new"> New </a> </LI>

<Li> <a href = "# none" Title = "Contact"> contact </a> </LI>

<Li> <a href = "# none" Title = ""> management </a> </LI>

<Li> <a href = "# none" Title = "subscribe"> subscription </a> </LI>

<Li> <a href = "# none" Title = "Ice Peak"> Ice Peak </a> </LI>

</Ul>

</Div>

The original structure of the menu is available. It can be seen that there are no meaningless labels, and each label has its own semantics. Let's look at it in the browser. Oh, it's really simple. It's just the original text, like what. Well, it's like the menu we use to order food in the restaurant. It may be simpler than that one, there is a dot in front of each menu! Oh, my God, it's a little better than our beautiful menu!

Style

Well, it is still a skeleton. Let's beautify it a little and add some simple styles. at least remove the dots and arrange them horizontally!

Good. Add some styles:

* {Margin: 0; padding: 0;}/* unify it into a uniform form. Otherwise, it will become ugly in various browsers */

Ul {list-style: None}/* remove the dot */

Li {float: Left; margin-left: 10px;}/* horizontal arrangement and some spacing. Don't squeeze me too tightly. */

Well, now let's take a look.

The skeleton is ready. Next, put on beautiful clothes for each menu item.

To meet the first requirement, you must first have a beautiful button and draw one by yourself. Oh, I am not an artist, so it's hard! However, don't be so ambitious. The network is so big that it's amazing. Maybe someone else has already done well. Google, I actually found one. Thank you!

With the designed button source code, it is really nice to save a part of the design. However, to create a three-state button, we need to modify it. Do you see the seventh goal? We need to make an adaptive button, so we need to do some processing on this button.

The three buttons are displayed as three states: move the mouse away, click, and move the mouse up. To do a sliding menu, you need to open a button from the center, place the left image on the left and the right image on the right. To adjust the length of the text, extend the width of the layer a little. However, this image has a complicated shadow effect, so it cannot be stretched at will. Otherwise, the effect will be different. We split it from the middle and stretch the left side of the right image to the front. 2.

 

Figure 1

So we first cut the image into six slices, and then merge the six images together. Why? Let's see how CSS Sprites works!

Figure 2

The first and second pictures form a normal menu style (default style), the third and fourth pictures form a tumble style, and the fifth and sixth pictures form the menu item style after the click.

We extract the shadow image into a very small background image.

Figure 3

All the required images are ready. Next, add the image to the menu. Two images are required for a button to be displayed. Everyone on Earth knows that only one image can be attached to one tag. (If you find that two images can be attached to one tag, please let me know in time and I will invite you to dinner !). Oh! In my menu structure, each item has exactly two labels. One is Li, which has a label and can be used to hold two images. Li is used to hold the picture on the left, and a is used to hold the picture on the right. I really admire myself. I can think of such a good idea, and I'm enjoying myself...

Don't be busy, oh, my God. How can I achieve the three mouse tumbling statuses if I install images like this? We should all know that at present, except for the damn IE6, other browsers support the Li: hover pseudo class. However, to be compatible with mainstream browsers (this is our 8th goal, don't forget !), This method does not work. IE6 can only apply pseudo classes to tags A. It does not apply to other tags!

Since IE6 can only apply the hover pseudo class to the label, we need to create an adaptive sliding door menu in the structure. It seems that only one label can be added to the label, then the menu structure will look like the following. (Note: here we start to change the structure. Although I have been trying to avoid this situation, it seems that this label is not a necessity to meet the requirements .)

<Li> <a href = "# none" Title = "Ice Peak"> <span> Ice Peak </span> </a> </LI>

We added a span container to the label, which included the text content. Now there are two tags. you can install two images. We place the picture on the right in the background of tag a and align it to the right. We place the picture on the left in the span tag and align it to the left. In this way, a complete button shape is displayed.

Fortunately, although a label is added, it is not completely speechless.

Well, we have almost finished our preparations. We should put on new clothes for the menu.

We want to make a menu with adaptive width, so we cannot set the menu width, so we cannot set the width as we do when creating a horizontal menu with fixed width, then float to the left. In this case, the width of each menu item is different. To define the width of each item separately, you must define an ID or class for each menu item, in addition, this method is not conducive to dynamic loop output of background programs.

What we need is to automatically arrange each menu item in a row from left to right like an inline element, so we need to display it in the way of intra-menu linking. OK, we will use display: inline, this is a very useful attribute: the parsed arrangement method can meet our basic requirements: the label elements are automatically arranged from left to right in a row, and the width of each item can be different.

If the above attributes can meet our needs, there will be no text below.

Although this attribute can meet the basic needs of our project, it has a very fatal weakness: it cannot set the width and height values. If you don't believe it, you can try it. It only shows the default height and width of the text. It is automatically hidden after the value of the width is exceeded. In this way, I have a background image. To show the image effect, we need to specify the width and height. This cannot make our results, so we are depressed! Fortunately, there is another property: Display: inline-block; which is what we need.

But... This property also has a fatal weakness, which can only be identified by ff3 and other advanced browsers. Other browsers can only bypass. Ah! So how important it is to unify the browser! It seems that hack is also a method of relief we have to force.

We understand the principles. We can make an adaptive menu based on the skills provided in the above two articles.

First, we will write the style of the image on the right, which is applied to the label of the child node of the Li element.

Li a {display: inline-block; padding-Right: 30px; padding-top: 10px; * padding-top: 0; padding-bottom: 13px; * padding-bottom: 0; Height: 36px; Background: URL (images/button.gif) No-repeat right-36px; text-Decoration: none; font-size: 12px; color: # FFF ;}

We first set the display: inline-block, and then we use padding to open its margin so that it has some space to fill the image. Note that the image path here is replaced with your own path. Set other styles, such as removing the underline, font color, and font size. Set the right alignment of the image.

Li a span {display: inline-block; padding-left: 30px; padding-top: 10px; * padding-top: 0; padding-bottom: 13px; padding-bottom: 0; Height: 36px; line-Height: 36px; Background: URL (images/button.gif) No-repeat left top; font-weight: bold ;}

The picture on the left of the button is placed in the span element, and its image is aligned to the left. It is also set to pad to open its width and height.

Li a, Li a span {display: inline; cursor: pointer ;}

Then they are set back to the inline mode to trigger the haslayout feature of IE.

In the above Code, we also see an hack application, * padding-bottom: 0; and * padding-top: 0;, which is used to solve the different effects of IE and FF browsers. I don't believe you can see what it will do after deleting it. There is a problem with the height of the IE extension.

Now it's time to write the effect of moving the mouse up.

Li A: hover {padding-Right: 30px; Background: URL (images/button.gif) No-repeat right-adjust PX ;}

Li A: hover span {padding-left: 30px; Background: URL (images/button.gif) No-repeat left-72px; font-weight: bold ;}

Next is the effect of clicking the mouse.

Li A: active {padding-Right: 30px; Background: URL (images/button.gif) No-repeat right-180px ;}

Li A: active span {padding-left: 30px; Background: URL (images/button.gif) No-repeat left-144px; font-weight: bold ;}

OK, it seems that the success is achieved. You can see it in different browsers, and it seems that the results can be satisfactory. Below is:

Figure 4

Now the CSS-only sliding menu is basically ready.

 

Behavior

 

The above effect seems to be another step away from my ideal menu. However, I am also confused.

1. if I click a menu, the dotted box with the focus is annoying.

2. You cannot highlight the selected items after clicking.

Solve the problem step by step!

To remove this dotted box, we can add onfocus = "This. Blur ();" to the label attribute, which is a very immediate method. Then you need to add some content in the structure, which may become the following structure:

<Li> <a href = "# none" Title = "Ice Peak" onfocus = "this. blur (); "> <span> Ice Peak blog </span> </a> </LI>

However, we should not forget to avoid interfering with the "structure" by "behavior" as much as possible. This is our requirement at the beginning. Therefore, this method can basically be rejected.

In addition, we want to record the selected menu items. There are many ways to create this method. The pure CSS method may create an ID for each menu item, then, use a style sheet to set the style of the highlighted menu that is called on different pages. However, this method adds some characters to the structure.

The above two solutions both need to embed something in the structure that should have been expressed by "actions". This will cause structural redundancy, poor readability, and a messy page.

I think it's time for js to make a debut...

I want to traverse all the labels under ul as soon as the page is loaded, and add a style to it automatically. This style is the style of Li A. We can change it to a class, let's name it "normal" to facilitate JS dynamic calling, and change Li A: hover to a class named "over" as the effect of JS dynamic calling of mouse moving, while Li: active is the selected status. The name is cur and all three of them are modified in the style sheet.

After loading the page, use the for loop to inject onclick, onmouseover, and onmouseout events to each menu a tag. Then we can discard the: Link, A: hover,: it is more convenient to control the highlighted effect of the selected menu. By the way, remove the annoying dotted box in this loop (although only one style can be used in FF, it is obviously not possible in IE !). Then, we use cookies to record the selected menu item ID and set it to 5 minutes before expiration. In this way, you can highlight the menu or remember it, no matter how malicious the screen is refreshed. (Whether to use the cookie method to maintain the highlight, which can be determined based on different project requirements. This method also has some bad points. If you have a good friend, you can talk about it !)

Several basic functions are created in JS, which looks like the following (for detailed code, see the source code ):

VaR temp;/* menu ID */

Function getobj (objname) {return (document. getelementbyid (objname ));}

Window. onload = function (){

VaR OBJ = getobj ("menu");/* ul ID */

VaR obj_a = obj. getelementsbytagname ("");

Number = obj_a.length;

For (VAR I = 0, j = obj_a.length; I <j; I ++ ){

Obj_a [I]. Index = I;

Obj_a [I]. classname = "normal ";

Obj_a [I]. onclick = function () {Click (this )};

Obj_a [I]. onmouseover = function () {overme (this )};

Obj_a [I]. onmouseout = function () {outme (this )};

Obj_a [I]. onfocus = function () {This. Blur ()};/* remove the dotted box under IE, and use the style to remove FF */

}

If (getcookie ("show_a ")! = NULL ){

Obj_a [getcookie ("show_a")]. classname = "cur ";

Temp = getcookie ("show_a ")

}

Else {

VaR OBJ = getobj ("menu ");

VaR obj_a = obj. getelementsbytagname ("");

Obj_a [0]. classname = "cur ";

// Move the mouse over

Function overme (o) {/* Code omitted, please refer to demo */}

// Effect after moving the mouse away

Function outme (o) {/* Code omitted, please refer to demo */}

// Effect after clicking the mouse

Function click (o) {/* Code omitted, please refer to demo */}

// Set cookie

Function setcookie (sname, svalue, expireminute) {/* Code omitted, please refer to demo */}

// Obtain the cookie

Function getcookie (sname) {/* Code omitted, please refer to demo */}

After adding the above js code, we controlled the interactive menu action and simplified the menu structure. The three layers were completely separated. In this way, we can achieve our ideal state without making too many changes to the structure. This structure directly loops when adding background code, and you only need to dynamically output the data in the menu text item.

Check whether your results are exactly the same in various mainstream browsers!

Figure 5

So far, a cool standard sliding door navigation menu is in your hands!

Conclusion: when making these cases, we should always pay attention to our own structure so that it can maintain good scalability. Eliminate redundant and non-semantic labels as much as possible, which is particularly important in a pipeline-like work environment. It brings great convenience to backend programs and makes your code look more comfortable! 

The Compatibility environment for this instance test is:

IE6/IE7/ff3/TT/opera9.63/Google browser passed the test. If you have other browsers, ask your friends to test them.

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.