Saturday, December 13, 2014

Flexbox: CSS Flexible Box Layout


The CSS3 Flexible Box, or flexbox, is a layout mode providing for the arrangement of elements on a page such that the elements behave predictably when the page layout must accommodate different screen sizes and different display devices. For many applications, the flexible box model provides an improvement over the block model in that it does not use floats, nor do the flex container’s margins collapse with the margins of its contents.
Many designers will find the flexbox model easier to use. Child elements in a flexbox can be laid out in any direction and can have flexible dimensions to adapt to the display space. Positioning child elements is thus much easier, and complex layouts can be achieved more simply and with cleaner code, as the display order of the elements is independent of their order in the source code. This independence intentionally affects only the visual rendering, leaving speech order and navigation based on the source order.
The defining aspect of the flex layout is the ability to alter its items’ width and/or height to best fill the available space on any display device. A flex container expands items to fill available free space, or shrinks them to prevent overflow.
The flexbox layout algorithm is direction-agnostic as opposed to the block layout, which is vertically-biased, or the inline layout, which is horizontally-biased. While the block layout works well for pages, it lacks sufficient definition to support application components that have to change orientation, resize, stretch, or shrink as the user agent changes, flips from vertical to horizontal, and so forth. Flexbox layout is most appropriate for the components of an application, and small-scale layouts, while the (emerging) Grid layout is intended for larger scale layouts. Both are part of a wider effort of the CSS Working Group to provide for greater interoperability of web applications with different user agents, different writing modes, and other demands on flexibility.

DESIGNATING A FLEXIBLE BOX

To designate the CSS for elements using this style, set the display property as follows:
display : flex
or
display : inline-flex
Doing so defines the element as a flex container and its children as flex items. The flex value makes the flex container a block-level element. The inline-flex value makes the flex container an atomic inline-level element.

UNNATURAL PLACEMENT

But your client isn’t satisfied yet. Instead of messing with the <div.content> she now wants the <footer> to come first, even before the <header>. Clients are crazy folks, you know. Well, Flexbox is also your friend in this case. Since we need to fiddle about not just at the inner elements but at the outer one the display: flex rule has to be stated for <div>. Since <header><div.main> and <footer> are stacked above we need to set a vertical context first, which is done with flex-direction: column. So if you ever want to change a row of elements into a column (or vice versa), you can use this property. Additionally the <footer> gets the order value of -1 as above so that it comes first. It’s as easy as that.
.ex {
 display: flex;
 flex-direction: column;
}

footer {
 order: -1;
}

PROPER ALIGNMENT

Flexbox also makes it very easy to align its children horizontally as well as vertically. All the elements within a container can be aligned with align-items, individual ones with align-self. But the alignment of the elements is dependent on the set flex-direction. If it is row (that means the elements run in a horizontal line), the alignment concerns the vertical axis; if it is column (that means the elements run in a vertical line), it concerns the horizontal axis. To center the image within <div.content/>, for example, you need to set display: flex for this container first and then the flex-direction to column so that they get stacked atop. Finally the image gets centered with align-self: center
.content {
 display: flex;
 flex-direction: column;
}

.content .img {
 align-self: center;
}
If all of the elements within <div.content/> need to be aligned the property align-items can be used. Set it to flex-end and they get pushed to the right (except for the image, which is individually centered above). The default left alignment is achieved with the value flex-start.
.content {
 align-items: flex-end;
}

JUSTIFY YOURSELF

Another property for alignment is justify-content, which is pretty handy to evenly divide the available space to various elements . Here we have an image bar and the four images are evenly distributed across the whole width, thanks to the value space-between.
.bar {
 display: flex;
 justify-content: space-between;
}
Another value would be space-around, which also provides for even division, but adds half of the gap width before the element and the other half after.

PURE FLEXIBILITY

Another strength of Flexbox is its ability to automatically distribute the available space to the elements of the container, which is set to display: flex. If you need three columns with equal width you’d normally have to calculate a little bit and come up with a width of 33.33% for each column. For such purposes Flexbox provides the flex property. To get three equal columns just set flex: 1
nav, .content, aside {
 flex: 1;
}
If you need the content area to be twice the width of <nav> (and <aside>) set flex: 2 for it and leave the other two at 1.

 FLEXBOX LAYOUT METHOD

In part one,we touched on how to harness the power of display:

In part 2 we’ll be taking a look on how to take this even further, and turn your flexbox layout into a fully-fledged responsive design!

A BRIGHT FUTURE

As you can see, Flexbox has great potential to make our lives so much easier if we need to set up a layout for a website. It’s rock solid (at least in the current version) and makes any hacks, collapsing containers or other weird stuff we have to deal with every day, obsolete. Hopefully the current syntax is the final one and every browser will interpret the properties in the same way prospectively.


Can web animation save flat design?


Can web animation save flat design?  Can web animation save flat design? animated submit button

Thursday, December 11, 2014

Native HTML5′s drag and drop


Having been a part of the Windows desktop for years, it was only a matter a time before Drag & Drop capability would come to browsers. In fact, Microsoft incorporated drag and drop into Internet Explorer 5.0 way back in 1999! With the emergence of Dynamic HTML, other browsers could also implement Drag & Drop. However, it required a lot of scripting to get it to work right. Now, HTML5’s native Drag & Drop capabilities promise to make our lives just a little bit easier.

A Work in Progress

Not to be a “Debbie Downer”, but at this early stage, HTML5’s Drag and Drop API is far from perfect. The way it’s supposed to work with all things HTML5 is that you include the feature for browsers that support it and those who don’t just have to do with a less rich experience. As nice as that would be, there is just too much of a disconnect between Internet Explorer and the DOM-compliant browser objects and document structure for such a dream to come to fruition. Even within the realm of the standards-compliant players, Opera, Firefox, Safari, and Chrome, there are many quirks and inconsistencies to negotiate. Nonetheless, the new HTML5 API is enough of a step forward over existing script-based ones to start using it.

Browser Support

HTML5 Drag & Drop is supported in Firefox 3.5+, Chrome 3.0+, Safari 3.0+. Opera support should follow soon enough. Support in Internet Explorer is not as cut and dry. Although it was the pioneer of Drag & Drop, Internet Explorer has supported draggging of images, links, and text since version 5.0. However, it wasn’t until version 10 that support for the draggable attribute was added. Version 10 goes a step further and provides the ability to drag files from the desktop to a webpage–a great compliment to the JS FileReader API.

Defining an Element as “Draggable”

By default, both images and link elements are draggable without any additional coding. If you want to drag a different element, you need to add a special attribute. In DOM-compliant browsers, a draggable node requires a “draggable” attribute which is set to “true”. As mentioned earlier, Internet Explorer is limited to images and links below version 10, since earlier versions don’t support the draggable attribute.
n the following example, the link element is draggable in all of the browsers mentioned above even without the draggable attribute. The <span> element is not draggable in Internet Explorer 9 or below:
<a href="#" id="toDrag">This is a draggable item</a>
<span draggable="true">This item is not draggable in IE 9!</span>
The following HTML markup contains a draggable link and image as well as <div> that will act as a drop area. Believe it or not, we’re already half done even though we haven’t written any scripting code!
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
<head>
<meta charset=utf-8 />
<title>A Basic Drag & Drop Demo</title>
<style>
#drop {
  min-height: 150px;
  width: 250px;
  border: 1px solid blue;
  margin: 10px;
  padding: 10px;
}
</style>
</head>
<body>
  <h1 align=center>A Basic Drag & Drop Demo</h1>
  <a href="http://www.robgravelle.com" id="text" draggable="true">This is a draggable item</a>
  <img id="ball" alt="ball (2K)" src="ball.gif" height="50" width="50" />
  <div id="drop"></div>
</body>
</html>

The JavaScript Code

Oddly enough, the way to tell the browser that an element can act as a drop zone is to cancel its dragover() and dragenter() events. The former is for DOM-compliant browsers while the latter applies to Internet Explorer.
Here then is the code to set up the drop as a dropoff point:
  var drop = document.getElementById('drop');

  function cancel(e) {
    if (e.preventDefault) e.preventDefault();
    return false;
  }

  //Tells the browser that we can drop on this target
  addEvent(drop, 'dragover', cancel);  //DOM event
  addEvent(drop, 'dragenter', cancel); //IE event
You’re probably unfamiliar with the addEvent() function. It’s part of the h5utils.js JavaScript library and is a browser agnostic method for adding event listeners. You can download the file via the “View raw file” link on the right-hand side of the page to include it in your own scripts. For your own edification, here is the addEvent() function code:
var addEvent = (function () {
  if (document.addEventListener) {
    return function (el, type, fn) {
      if (el && el.nodeName || el === window) {
        el.addEventListener(type, fn, false);
      } else if (el && el.length) {
        for (var i = 0; i < el.length; i++) {
          addEvent(el[i], type, fn);
        }
      }
    };
  } else {
    return function (el, type, fn) {
      if (el && el.nodeName || el === window) {
        el.attachEvent('on' + type, function () { return fn.call(el, window.event); });
      } else if (el && el.length) {
        for (var i = 0; i < el.length; i++) {
          addEvent(el[i], type, fn);
        }
      }
    };
  }
})();

Coding the Drop Event

To respond to the drop event, all you have to do is add an event handler to it as follows:
  addEvent(drop, 'drop', function (e) {
    if (e.preventDefault) e.preventDefault(); // stops the browser from redirecting off to the text.
    this.innerHTML = "<strong>Done!</strong>";
    this.style.backgroundColor="#CCCC00";

    return false;
  });
</script>
The above code presents a message in the drop element and changes the background color. Notice that we have to call the Event.preventDefault() method and return “false” because the browser will automatically treat the object as a link and attempt to redirect otherwise. If we were to remove that line, the ball image would be presented in a new page and draggable text would forward to the page contained in the link’s HREF attribute. That can be a desirable consequence in some instances so it’s good to know how to toggle the redirecting behavior on and off.

Conclusion

Today we explored the basics of the HTML5 Drag & Drop API. Next time, we’ll learn how the dataTransfer property can be used to shuttle data and document elements from one part of the page to another.

Tuesday, December 9, 2014

How to use the new HTML5 Audio element


Several exciting elements to come out of the HTML5 specification include presenting native multimedia content within browsers, and specifically addressing the aspects for providing audio and video content within web pages utilizing a standardized format. The HTML5 audio <audio> element utilizes a standard way of embedding audio digital content, thus allowing web developers the freedom of not having to rely solely on plugins to associate with the content file types. Once enabled and fully implemented as a standard, there will be no requirement for a browser plugin, as the HTML5 specifies a standard way to include audio content with the <audio> elements.  So will these multimedia elements replace Flash?
The audioelement in its simplest form is represented as specifying a single source src=”url”:
<audio src=""></audio>
The audio element offers the option for a control attribute in the form controls=”controls” for adding play, pause, and volume controls, as in the example:
<audio src="music.mp3" controls="controls">
</audio>

Attributes

In addition to the source (src=”url”) and controls (controls=”controls”) attributes, listed below are the five attributes, their associated values, and a short description:

Table 1

How to use the new HTML5 Audio element 09012011 tab1a
In reference to the “autoplay” attribute, and as a rule of thumb, in most instances new visitors to a website will frown upon any audio instantly playing as they navigate into a website. However, there are some instances when autoplaying audio on websites is acceptable; sites that promote music, a band, a musician, or other aural artistic forms, would probably benefit from autoplaying a sampling of a performance.
The <audio> element can play sound files as well as an audio streaming, and there are three main audio file formats supported for the <audio> element:
  • Ogg – with the extension .ogg and called “Vorbis”
  • MP3 -
  • Wav -
As a best practice, it is advisable to insert fallback statement content between the <audio> and </audio> tags for browsers that do not support the audio element (more examples of fallback support will be provided below):
<audio src=" music.mp3" controls="controls">
Your browser does not support the HTML5 audio element.
</audio>

Browser support for <audio> element

Currently the listed browsers support the following audio file codec and formats as listed in the matrix below:

Table 2

How to use the new HTML5 Audio element 09012011 tab2
This is an example of a single audio source from the Internet Archives.org of a Roy Rogers radio show “The Horse Thieves of Paradise Valley”:
<audio src="http://ia700204.us.archive.org/13/items/The_Roy_Rogers_Show/Roy_Rogers_480905_Horse_Thieves_of_Paradise_Valley.mp3"
controls="controls">Your browser does not support the HTML5 audio element.
</audio>

Sources

Solving the cross-browser functionality issue, you can list several sources for the audio clip as long as there is more than one file type available. Browsers will attempt to load the source file in the coded order, and if the file fails to load, the browser will move onto the next source within the <audio> element. The example below shows how a single audio can be rendered in several browsers by providing the two file format sources, in this instance .ogg and mp3:
    <section>
        <h1>HTML5 Audio Element</h1>
        <h2>The Roy Rogers Show</h2>
        <h3 align="left">Horse Thieves of Paradise Valley</h3>
        <audio controls="controls">
        Your browser does not support the audio element.
            <source src="http://ia700204.us.archive.org/13/items/The_Roy_Rogers_Show/Roy_Rogers_480905_Horse_Thieves_of_Paradise_Valley.mp3" type="audio/mp3" /></source>
            <source src="http://.../audio/Roy_Rogers_480905_Horse_Thieves_of_Paradise_Valley.ogg" type="audio/ogg" /></source>
        </audio>
    </section>

Cross-browser support and fallback

If the selected browser does not render the .mp3, .wav, or the .ogg file format, then you could add another fallback allowing Flash to play the file. Another option is employing the use of the jPlayer HTML5 Audio Checker which tests browsers for HTML5 <audio> element support and for Audio() object support using “feature sniffing” utilizing JQuery and JavaScript to check for audio element support.
The specification also allows the use of enhanced audio API features to directly generate and manipulate audio streams from JavaScript code; several controls using the API extensions include:
  • play() – plays the audio
  • pause() – pauses the audio
  • canPlayType() – examines the browser to establish whether the given mime type can be played
  • buffered() – attribute that specifies the start and end time of the buffered part of the file
An example of JavaScript calling and playing audio:
// Call and play audio via JavaScript
$(document).ready(function() {
       var audioElement = document.createElement('audio');
       audioElement.setAttribute('src', ‘audio_file.ogg');
       audioElement.load()
       audioElement.addEventListener("load", function() {
               audioElement.play();
               $(".duration span").html(audioElement.duration);
               $(".filename span").html(audioElement.src);
       }, true);
       $('.play').click(function() {
               audioElement.play();
       });
An example of JavaScript to pause the audio:
       $('.pause').click(function() {
               audioElement.pause();
       });
Determining what format the browser will use with JavaScript code is a little more complex than the simple fallback model for the <audio> element source. Using the canPlayType() API method to pretest the browser’s file format capabilities, it takes an audio mime type, and codec (optional) parameters, and returns one of three strings: empty, maybe, or probably.
The following JavaScript code example tests for three file types .mp3, .ogg, and .aac audio file formats:
  <script>
 function checkAudioCompat() {x
       var myAudio = document.createElement('audio');
      if (myAudio.canPlayType) {
          // CanPlayType returns maybe, probably, or an empty string.
          if ( "" != myAudio.canPlayType('audio/mpeg')) {
              alert("mp3 supported");
          }
          if ( "" != myAudio.canPlayType('audio/ogg; codecs="vorbis"')) {
              alert("ogg supported");
          }
         if ( "" != myAudio.canPlayType('audio/mp4; codecs="mp4a.40.5"')) {
              alert("aac supported");
          }
      }
      else {
         alert("no audio support");
      }
  }
</script>
Because the canPlayType() API can return more than one audio file format, it might be a good practice to test for hierarchy, and then choosing the best fit for the file format and browsers used by the customer.

Native HTML5′s drag and drop


Having been a part of the Windows desktop for years, it was only a matter a time before Drag & Drop capability would come to browsers. In fact, Microsoft incorporated drag and drop into Internet Explorer 5.0 way back in 1999! With the emergence of Dynamic HTML, other browsers could also implement Drag & Drop. However, it required a lot of scripting to get it to work right. Now, HTML5’s native Drag & Drop capabilities promise to make our lives just a little bit easier.

A Work in Progress

Not to be a “Debbie Downer”, but at this early stage, HTML5’s Drag and Drop API is far from perfect. The way it’s supposed to work with all things HTML5 is that you include the feature for browsers that support it and those who don’t just have to do with a less rich experience. As nice as that would be, there is just too much of a disconnect between Internet Explorer and the DOM-compliant browser objects and document structure for such a dream to come to fruition. Even within the realm of the standards-compliant players, Opera, Firefox, Safari, and Chrome, there are many quirks and inconsistencies to negotiate. Nonetheless, the new HTML5 API is enough of a step forward over existing script-based ones to start using it.

Browser Support

HTML5 Drag & Drop is supported in Firefox 3.5+, Chrome 3.0+, Safari 3.0+. Opera support should follow soon enough. Support in Internet Explorer is not as cut and dry. Although it was the pioneer of Drag & Drop, Internet Explorer has supported draggging of images, links, and text since version 5.0. However, it wasn’t until version 10 that support for the draggable attribute was added. Version 10 goes a step further and provides the ability to drag files from the desktop to a webpage–a great compliment to the JS FileReader API.

Defining an Element as “Draggable”

By default, both images and link elements are draggable without any additional coding. If you want to drag a different element, you need to add a special attribute. In DOM-compliant browsers, a draggable node requires a “draggable” attribute which is set to “true”. As mentioned earlier, Internet Explorer is limited to images and links below version 10, since earlier versions don’t support the draggable attribute.
n the following example, the link element is draggable in all of the browsers mentioned above even without the draggable attribute. The <span> element is not draggable in Internet Explorer 9 or below:
<a href="#" id="toDrag">This is a draggable item</a>
<span draggable="true">This item is not draggable in IE 9!</span>
The following HTML markup contains a draggable link and image as well as <div> that will act as a drop area. Believe it or not, we’re already half done even though we haven’t written any scripting code!
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
<head>
<meta charset=utf-8 />
<title>A Basic Drag & Drop Demo</title>
<style>
#drop {
  min-height: 150px;
  width: 250px;
  border: 1px solid blue;
  margin: 10px;
  padding: 10px;
}
</style>
</head>
<body>
  <h1 align=center>A Basic Drag & Drop Demo</h1>
  <a href="http://www.robgravelle.com" id="text" draggable="true">This is a draggable item</a>
  <img id="ball" alt="ball (2K)" src="ball.gif" height="50" width="50" />
  <div id="drop"></div>
</body>
</html>

The JavaScript Code

Oddly enough, the way to tell the browser that an element can act as a drop zone is to cancel its dragover() and dragenter() events. The former is for DOM-compliant browsers while the latter applies to Internet Explorer.
Here then is the code to set up the drop as a dropoff point:
  var drop = document.getElementById('drop');

  function cancel(e) {
    if (e.preventDefault) e.preventDefault();
    return false;
  }

  //Tells the browser that we can drop on this target
  addEvent(drop, 'dragover', cancel);  //DOM event
  addEvent(drop, 'dragenter', cancel); //IE event
You’re probably unfamiliar with the addEvent() function. It’s part of the h5utils.js JavaScript library and is a browser agnostic method for adding event listeners. You can download the file via the “View raw file” link on the right-hand side of the page to include it in your own scripts. For your own edification, here is the addEvent() function code:
var addEvent = (function () {
  if (document.addEventListener) {
    return function (el, type, fn) {
      if (el && el.nodeName || el === window) {
        el.addEventListener(type, fn, false);
      } else if (el && el.length) {
        for (var i = 0; i < el.length; i++) {
          addEvent(el[i], type, fn);
        }
      }
    };
  } else {
    return function (el, type, fn) {
      if (el && el.nodeName || el === window) {
        el.attachEvent('on' + type, function () { return fn.call(el, window.event); });
      } else if (el && el.length) {
        for (var i = 0; i < el.length; i++) {
          addEvent(el[i], type, fn);
        }
      }
    };
  }
})();

Coding the Drop Event

To respond to the drop event, all you have to do is add an event handler to it as follows:
  addEvent(drop, 'drop', function (e) {
    if (e.preventDefault) e.preventDefault(); // stops the browser from redirecting off to the text.
    this.innerHTML = "<strong>Done!</strong>";
    this.style.backgroundColor="#CCCC00";

    return false;
  });
</script>
The above code presents a message in the drop element and changes the background color. Notice that we have to call the Event.preventDefault() method and return “false” because the browser will automatically treat the object as a link and attempt to redirect otherwise. If we were to remove that line, the ball image would be presented in a new page and draggable text would forward to the page contained in the link’s HREF attribute. That can be a desirable consequence in some instances so it’s good to know how to toggle the redirecting behavior on and off.

Conclusion

Today we explored the basics of the HTML5 Drag & Drop API. Next time, we’ll learn how the dataTransfer property can be used to shuttle data and document elements from one part of the page to another.

HTML5 download Attribute

 

HTML5 introduced a lot of new APIs, input types and attributes for forms. However, a lot of small additions were made such as the download attribute.

The download attribute is ideal when your browser won’t automatically download the file; images, other web pages and sometimes PDFs. The download attribute is used to give the browser a native way to download these files automatically without having to fall back on Javascript. This comes in handy for websites that use a lot of images which users can download e.g. image upload sites.

What is the download attribute?

The download attribute is as simple as adding a new attribute to your link tag:
<a href="/images/your_image.jpg" download>Download image</a>
Using the download attribute, we can override the default file name that should automatically be saved even when it isn’t present on your server. This tackles any problems when websites use long dynamically created image names that we want to replace with a more simple and user-friendly file name. To provide a name you simply add a value to the attribute as seen below:
<a href="/images/some_long_file_name_123_123_0192.jpg" download="MyImage">Download image</a>
You don’t need to worry about adding the extension, your browser will automatically add the correct file extension onto the downloaded file.
This attribute is extremely useful in cases where generated files are in use — the file name on the server side needs to be incredibly unique, but the download attribute allows the file name to be meaningful to user.  The download attribute is one of those enhancements that isn’t incredibly sexy but is a practical and easy to add.
Overall, with everything else that has been added to HTML5, the download attribute is a very small part but still, it definitely has its uses in today’s applications for both usability and simplification.

Fixed Navigation Bar in CSS & HTML


If you want to make a navigation bar which will always be on the top of the page, in this tutorial you are going to learn how to do it. Here we will use basic HTML and CSS (Cascading Style Sheet) for it.
Before starting to create it let me tell you a good news and a bad news.
Good News : Fixed Navigation Bar in CSS & HTML supports all major browsers (including IE7 and higher)
Bad News : IE7 and lower doesn’t support the Shadow Effect which we are gonna use to make it look good. See the live demo of the navigation bar in IE then you will get to know what’s the problem.
If you want the shadow effect then you need to create an image with the effect and set it as background image of your “Navigation Bar” a.k.a “DIV”.
Now we are ready to develop it.
HTML Code for menu : Add this code inside body.
<div id=”nav”>
<p><a href=”#”>TheCodePress<span>.blogspot.com</span></a></p>
<ul id=”navigation”>
<li><a href=”#”>Home</a></li>
<li><a href=”#”>My Blog</a></li>
<li><a href=”#”>Tutorials</a></li>
<li><a href=”#”>Downloads</a></li>
<li><a href=”#”>About</a></li>
</ul>
</div>
CSS Code for HTML body : The body margin should be 0px.
body
{
margin:0px;
}
After making your HTML > Body margin to 0px you will not see a big difference. Now let’s design our Navigation bar which Div ID is “nav”.
CSS Code for “nav” : 
#nav
{
background-color:#262626;
width:100%;
height:50px;
box-shadow: 0px 1px 50px #5E5E5E;
position:fixed;
top:0px;
}
Now i’m going to design the title of the page, if you want to design same is i designed you can use the code or you can design as you want.
CSS Code for class “title” and “subtitle” : 
.title
{
color:#EDEDED;
font-family:verdana;
font-size:25px;
width:350px;
margin-top:6px;
margin-left:150px;
font-weight:bold;
float:left;
}
.subtitle
{
color:#EDEDED;
font-family:verdana;
font-size:15px;
}
Now we are going to design the links of our navigation menu.
CSS Code for ID “Navigation”, li, and Links :
#navigation
{
list-style-type:none;
}
li
{
display:inline;
padding:10px;
}
#nav a
{
font-family:verdana;
text-decoration:none;
color:#EDEDED;
}
#nav a:hover
{
color:#BDBDBD;
}
ok here you are done with navigation bar, i’ll also add some content.
HTML Code for content : 
<div id=”body”>
<!–Add your content HERE–>
</div>
After adding content in a div which ID is “body” you will see a problem, some of the content which’s on the top is unable to see because navigation bar is overlaying it. To make it proper you will need the margin-top of your content to be around 80px or more than that. In this post i’m using 80px.
CSS Code for “body” : 
#body
{
width:850px;
margin:0px auto;
margin-top:80px;
font-family:verdana;
}
Now you are completely done with the Fixed Navigation Bar.

CSS Specificity: Things You Should Know


CSS Specificity is one of the most difficult concepts to grasp in Cascading Stylesheets. The different weight of selectors is usually the reason why your CSS-rules don’t apply to some elements, although you think they should have. In order to minimize the time for bug hunting you need to understand, how browsers interpret your code. And to understand that, you need to have a firm understanding on how specificity works. In most cases such problems are caused by the simple fact that somewhere among your CSS-rules you’ve defined a more specific selector.
CSS Specificity isn’t simple. However, there are methods to explain it in a simple and intuitive way. And that’s what this article is all about. You’ll understand the concept if you love Star Wars. Really.
Let’s take a look at some important issues related to CSS Specificity as well as examples, rules, principles, common solutions and resources.
  • You can find the most important things you should know about CSS specificity in a brief overview at the beginning of the article.

CSS Specificity: An Overview

  1. Specificity determines, which CSS rule is applied by the browsers.
  2. Specificity is usually the reason why your CSS-rules don’t apply to some elements, although you think they should.
  3. Every selector has its place in the specificity hierarchy.
  4. If two selectors apply to the same element, the one with higher specificity wins.
  5. There are four distinct categories which define the specificity level of a given selector: inline styles, IDs, classes+attributes and elements.
  6. You can understand specificity if you love Star Wars: CSS Specificity Wars.
  7. You can understand specificity if you love poker: CSS Specificity for Poker Players
  8. When selectors have an equal specificity value, the latest rule is the one that counts.
  9. When selectors have an unequal specificity value, the more specific rule is the one that counts.
  10. Rules with more specific selectors have a greater specificity.
  11. The last rule defined overrides any previous, conflicting rules.
  12. The embedded style sheet has a greater specificity than other rules.
  13. ID selectors have a higher specificity than attribute selectors.
  14. You should always try to use IDs to increase the specificity.
  15. A class selector beats any number of element selectors.
  16. The universal selector and inherited selectors have a specificity of 0, 0, 0, 0.
  17. You can calculate CSS specificity with CSS Specificity Calculator.
  18. What is Specificity?

    • Specificity determines, which CSS rule is applied by browsers. “Specificity is a type of weighting that has a bearing on how your cascading style sheet (CSS) rules are displayed.” [Understanding Specificity]
    • Selector specificity is a process used to determine which rules take precedence in CSS when several rules could be applied to the same element in markup. [Selector Specificity]
    • Every selector has its specificity. “All rules in your CSS carry a specificity rating regardless of selector type, although the weighting that is given to each selector type varies and will ultimately affect the styling of your web documents.” [Understanding Specificity]
    • If two selectors apply to the same element, the one with higher specificity wins.

    Specificity hierarchy

    • Every selector has its place in the specificity hierarchy. There are four distinct categories which define the specificity level of a given selector:1. Inline styles (Presence of style in document).
      An inline style lives within your XHTML document. It is attached directly to the element to be styled. E.g. <h1 style="color: #fff;">2. IDs (# of ID selectors)
      ID is an identifier for your page elements, such as #div.3. Classes, attributes and pseudo-classes (# of class selectors).
      This group includes .classes, [attributes] and pseudo-classes such as :hover, :focus etc.
      4. Elements and pseudo-elements (# of Element (type) selectors).
      Including for instance :before and :after.
    If you don’t know what exactly each of these terms stands for, you can take a look at the brief overview of them; in the last section of this article.

    How to measure specificity?

    • Memorize how to measure specificity. “Start at 0, add 1000 for style attribute, add 100 for each ID, add 10 for each attribute, class or pseudo-class, add 1 for each element name or pseudo-element. So in
      body #content .data img:hover
      the specificity value would be 122 (0,1,2,2 or 0122): 100 for #content, 10 for .data, 10 for :hover, 1 for body and 1 for img.” [CSS Specificity]
    • Alternative way: “Count the number of ID attributes in the selector (= a). Count the number of other attributes and pseudo-classes in the selector (= b). Count the number of element names and pseudo-elements in the selector (= c). Concatenating the three numbers a-b-c gives the specificity. [CSS Selector Specificity]
    • CSS Specificity Wars – Cheat Sheet
      To help me understand calculating specificity better I made a chart based on the following specificity (or Sith power) values. Each character (selector) is given its own Sith power (specificity value) depending on how powerful they are in the ways of the Dark Side. A storm trooper is less powerful than Vader who is in turn less powerful than the Emperor.
    • Specificity Example

      • Consider three code fragments:
        A: h1
        B: #content h1
        C: <div id="content">
        <h1 style="color: #fff">Headline</h1>
        </div>
        The specificity of A is 0,0,0,1 (one element), the specificity of B is 0,1,0,1 (one ID reference point and one element), the specificity value of C is 1,0,0,0, since it is an inline styling.
        Since
        0001 = 1 < 0101 = 101 < 1000,
        the third rule has a greater level of specificity, and therefore will be applied. If the third rule didn’t exist, the second rule would have been applied.

Multiple Columns Layout With CSS3


Creating a column on the Web is a totally different story. It’s quite difficult. In fact, not too long ago you may need to divide the content manually into some divs and float it to the right or left, then specify the width, padding, margin, borders and so on.
But, things are now much simplified with the CSS3 Multi Column Module. As the name clearly implies, this module allows us to divide content into the columned layout we see in newspapers or magazines.

Browser Support

Multiple columns are currently supported in all browsers – Firefox 2+, Chrome 4+, Safari 3.1+ and Opera 11.1 – except, as predicted, Internet Explorer, but the next version, IE10, seems to have started providing support for this Module.
For the rest of the browsers, in order for it to work, Firefox still needs the -moz- prefix, while Chrome and Safari need the -webkit- prefix. Opera doesn’t require any prefixes, so we can just using the official properties.

Create Multiple Column

Before we create the columns, we have prepared some text paragraphs for the demonstration, wrapped inside the HTML5<article> tag, as follow;
    1. <article>
    2.     Lorem ipsum dolor sit amet, consectetur adipiscing elit. Nunc libero magna, venenatis quis aliquet et,
    3.     rutrum in augue. Donec vel tempor dolor. Donec volutpat fringilla porta. Suspendisse non nulla tortor.
    4.     Quisque commodo ornare mi, sit amet aliquet justo bibendum non. Integer bibendum convallis sapien, sit
    5.     amet tincidunt orci placerat in. Integer vitae consequat augue.

    6.     //and so on
    7. </article>
…and specify the width for 600px from the style sheet, that’s it.
Now, let’s start creating the columns.
In the example below, we will divide the content into two columns with the column-count property. This property will tell the browser to render the content into columns by the specified number and let the browser decide the proper width for each column.

Column Gap

Column Gap define the spaces that separate each column. The gap value can be stated in em or px, but as stated in the spec the value cannot be negative.
    1. article {
    2.     -webkit-column-gap: 30px;
    3.     -moz-column-gap: 30px;
    4.     column-gap: 30px;
    5. }

Column Rule

Should you want to add borders between the column, you can use the column-rule property, which works very similar to the border property. So, let’s say, if we want to put a dotted border between the column, we can write;
    1. article {
    2.     -moz-column-rule: 1px dotted #ccc;
    3.     -webkit-column-rule: 1px dotted #ccc;
    4.     column-rule: 1px dotted #ccc;
    5. }

Column Span

This property works quite similar to the colspan in table tag. The common implementation of this property is to span the content’s headline across all columns. Here is an example.
    1. article h1 {
    2.     -webkit-column-span: all;
    3.     column-span:all;
    4. }
In the example above we defined the h1 to span across all columns, and if the column span is specified, 1 will be taken as the default. Unfortunately this property, at the time of this writing, only works in Opera and Chrome.

Final Thoughts

That’s all for now, we have come through all the essential stuff to create multiple columns with CSS3, and as we have mentioned in the beginning, this module works very well in modern browsers but it doesn’t work yet in Internet Explorer, but should you insist to apply Multiple Column in unsupported browsers, you can use this JavaScript library to mimic this Module functionality.
Ultimately, we hope that you now have a fairly good understanding on how to create columns with CSS3, and if you have time for experiments, feel free to share your methods and results in the comment box below. Thank you for reading this post and have fun.

Mobile friendly contact forms


No one likes filling out forms. This is an axiom. A good contact form is a contact form, which is comfortable for site visitors. Period. A contact form, designed in a visitor friendly way, is never an accident. There are too many things to consider: form responsiveness, label placement, form design or suggestions you add. The world admires people who has brilliant intuition, but, for the rest of us, there is only one working formula: MEASURE and CHANGE, and then MEASURE and CHANGE again. Anyone can select the measurement tool they want to use: which one they like better, Google analytics or the amount of cash he has in his pocket. Easy Contact Forms is a tool helping to change a site’s front door (Aka a contact form). A minute will be enough to change the contact form layout. A few minutes will be enough to add several fields. Testing the results of the improvements on every 100 or so of visitors, you will eventually make your contact form friendly and comfortable for your site visitors. Easy Contact Forms will help you.
Form input fields:
input styled
input[type=text], input[type=url], input[type=email], input[type=password], input[type=tel] {
  -webkit-appearance: none; -moz-appearance: none;
  display: block;
  margin: 0;
  width: 100%; height: 40px;
  line-height: 40px; font-size: 17px;
  border: 1px solid #bbb;
}
Other forms of input control:
Styled form controls
input[type=checkbox] {
 width: 44px; height: 44px;
 -webkit-border-radius: 22px; -moz-border-radius: 22px; border-radius: 22px;
 border: 1px solid #bbb;
}

Reasonable anti-spam protection and several validation layers.

When we say reasonable, we’re assuming that you know how to increase the contact form anti-spam protection when it is necessary. Hidden fields, along with several built-in anti-spam filters, will do the job transparently for site visitors. Easy Contact Forms supports both server and client side contact form submission data validation. Client side contact form validation guarantees that a site visitor gets instant feedback, allowing making quick corrections. Server side validation guarantees that a contact form will work in browsers, when JavaScript is disabled. Server side validation plays a crucial role of contact form’s second line of defense.

Use HTML5 input types appropriate keyboard

<label for=”website”>Website:</label> <input type=”url” name=”website” placeholder=”www.yourwebsite.com” />
URL keyboard
<label for=”tel”>Tel:</label> <input type=”tel” name=”tel” placeholder=”Your telephone number” />
Tel keyboard
<label for=”email”>Email:</label> <input type=”email” name=”email” placeholder=”you@yourwebsite.com” />
Email keyboard
<label for=”time”>Time:</label> <input type=”time” name=”time” placeholder=”9:00 AM” />
Time picker

Easy to use GUI.

Easy Contact Forms have a lot of useful GUI features.
  • Ajax based contact form settings GUI.
  • Advanced data filtering and scrolling.
  • Tab based interfaces.
  • Splash screens and tooltips.

Making CSS Count Backwards


Did you know that CSS Counters can go backwards?
Neither did I until I needed it, and I discovered that the counter-reset and counter-increment properties can be “seeded” with extra numbers, intended to allow for more flexible numbering, which can also be used to make them count backwards!

Counting Forwards

The basic idea with counters is that they allow you to implement number-systems in CSS, essentially replacing and supplementing ordered-list attributes like value and start. With two properties, you declare the name of a counting variable in a base selector, then increment it in an instance selector; the result is then typically output using the content property. Here’s a simple example, that re-creates the numbering of a standard ordered-list :
ol
{
    list-style-type:none;
    counter-reset:item;
}
ol > li
{
    counter-increment:item;
}
ol > li:before
{
    content:counter(item) ". ";
}
But as I said earlier, you can “seed” both these properties with additional values, so that they start from a different number and/or count in different steps. Here’s another example, this time starting from ten and counting up in twos :
ol
{
    list-style-type:none;
    counter-reset:item 10;
}
ol > li
{
    counter-increment:item 2;
}
ol > li:before
{
    content:counter(item) ". ";
}

Counting Backwards!

Now here’s the cunning bit! The additional value in counter-increment doesn’t have to be positive, it can also be zero or negative. So here’s an example of a counter that goes backwards from ten to one:
ol
{
    list-style-type:none;
    counter-reset:item 11;
}
ol > li
{
    counter-increment:item -1;
}
ol > li:before
{
    content:counter(item) ". ";
}
The thing to note is how we have to start counter-reset one-count higher than the highest number we want to display, because the iterating property counter-increment has already counted once when the first element is displayed (it’s counted that element).
Of course the fact that we have to hard-code the starting number at all makes this difficult to use in the wild, because the lists it encounters will generally have different numbers of items. The thing to do then is split the rules between a stylesheet and an inline style rule.

Production Code

So first we have the following stylesheet rules, which define an activating class, and the counting rule (there are also a couple of CSS hacks for IE6 and IE7, to restore their normal list-style since the counters won’t work):
ol.count-backwards
{
    list-style-type:none;
}
ol.count-backwards > li
{
    counter-increment:start-from -1;
}
ol.count-backwards > li:before
{
    content:counter(start-from) ". ";
}

* html ol.count-backwards { list-style-type:decimal; }
*+html ol.count-backwards { list-style-type:decimal; }
Then we instantiate a counter instance with a counter-reset style, defining the starting number (or rather, one-higher than the starting number, as we’ve seen). I’ve used "start-from" as the counter name so that it’s easy to remember what it is and what it does :
<ol style="counter-reset:start-from 11">
    <li>In tenth place..</li>
    <li>In ninth place..</li>
    <li>In eighth place..</li>
    <li>In seventh place..</li>
    <li>In sixth place..</li>
    <li>In fifth place..</li>
    <li>In fourth place..</li>
    <li>In third place..</li>
    <li>In second place..</li>
    <li>In first place..</li>
</ol>
We can even define additional class rules to implement different types of counter. Here’s one for lower-case greek :
ol.count-backwards.lower-greek > li:before
{
    content:counter(start-from, lower-greek) ". ";
}
But what’s it all for? Well, I wanted to make an archive list of blog posts for my site, listing the most-recent at the top. Since the first and earliest is then at the bottom, this means that the list needs to count down.
And I’m sure you can think of your own situations where this might be useful, and handy to have a way of implementing instantly, without the inevitable output-lag of doing it with scripting.
If the lack of IE6/7 bothers you, you could always add a scripting layer as well…

How to create custom control for user rating




 


 

 

CSS Animation


We have another cool new CSS feature to talk about: animation specified in CSS. There is a lot of ground to cover here, so we’ll start with the basics first.
The simplest kind of animation that we’ve added support for is called a transition. Normally when the value of a CSS property changes, the rendered result is instantly updated, with the element in question changing immediately from the old property value to the new property value. Transitions describe how to instead execute an animation from the old state to the new state over time.
Transitions are specified using the following properties:
transition-property – What property should animate, e.g., opacity.
transition-duration – How long the transition should last.
transition-timing-function – The timing function for the transition (e.g., linear vs. ease-in vs. a custom cubic bezier function).
transition – A shorthand for all three properties.
Here is a simple example:
div {
  opacity: 1;
  -webkit-transition: opacity 1s linear;
}

div:hover {
  opacity: 0;
}
This div will fade out when hovered over. In browsers that do not support this animation, there will be graceful degradation, as the div will simply fade out immediately.
Each of these properties supports a comma separated list of values, like CSS3 multiple backgrounds, which allows different transitions for individual properties to be described in a single style rule. Each value in the list corresponds to the value at that same position in the other properties.
For example:
div {
  -webkit-transition-property: opacity, left;
  -webkit-transition-duration: 2s, 4s;
}
In the above style rule, opacity will animate over 2 seconds, but left will animate over 4 seconds.
Some very complex properties can actually be animated. Take, for example, the new -webkit-transform property. Here’s an example of a simple spin effect using -webkit-transform and -webkit-transition.
<div style="-webkit-transition: -webkit-transform 3s ease-in"
  onclick="this.style.webkitTransform='rotate(360deg)'">
This div will do a spin when clicked!
</div>
This div will do a spin the first time it is clicked!
Borders can also be animated. The following box has a simple border animation where the border will both grow in thickness and change color when the box is hovered.
This div will acquire a slightly thicker blue border when hovered.
Note with the hovering examples that the animation will reverse itself when the mouse moves out of the div. Any time the property changes value, the animation will simply start again with the current position as the from value and the new value as the destination. The transition properties of the source state are used to figure out how to animate to the new target state.
The key points to understand about transitions are:
(1) They are implicit animations. Scripts and stylesheets can be written as normal, and the animations will simply happen implicitly as the properties change values.
(2) They degrade gracefully. Browsers that do not support transitions simply won’t animate, but otherwise all code and style rules can remain the same.
Here are more detailed descriptions of the properties. All of these properties can take multiple comma-separated values.
transition-property
Values: none | all | <property>
Initial Value: all
Description: Specifies what property triggers an animation. A value of none means there is no transition. A value of all means that every animatable property triggers an animation. Otherwise an animation will only trigger when the exact specified property changes value.
transition-duration
Values: <time>
Inital Value: 0
Description: Specifies how long the transition should take. The default is 0.
transition-timing-function
Values: ease | linear | ease-in | ease-out | ease-in-out | cubic-bezier(x1, y1, x2, y2)
Initial Value: ease
Description: The transition-timing-function property describes how the animation will proceed over time. Keywords can be used for common functions or the control points for a cubic bezier function can be given for complete control of the transition function. To specify a cubic bezier function, you give an X and Y values for 2 of the control points of the curve. Point P0 is implicitly set to (0,0) and P3 is implicitly set to (1,1). These 4 points are used to compute a cubic bezier curve.
The timing function keywords have the following definitions:
linear – The linear function just returns as its output the input that it received.
defaultease – The default function, ease, is equivalent to cubic-bezier(0.25, 0.1, 0.25, 1.0).
ease-in – The ease-in function is equivalent to cubic-bezier(0.42, 0, 1.0, 1.0).
ease-out – The ease-out function is equivalent to cubic-bezier(0, 0, 0.58, 1.0).
ease-in-out – The ease-in-out function is equivalent to cubic-bezier(0.42, 0, 0.58, 1.0)
cubic-bezier – Specifies a cubic-bezier curve whose P0 and P3 points are (0,0) and (1,1) respectively. The four values specify points P1 and P2 of the curve as (x1, y1, x2, y2).
In future posts I’ll go into transitions in more detail and also talk about another feature we’re adding: explicit animations. We are also preparing a more detailed proposal (full of intimidating spec language) that covers our thoughts on transforms, animation and other advanced visual effects.

Guidelines For Defensive HTML and CSS Rendering


Working as a web developer can suck oftentimes, especially when rendering codes of the client’s project. It it becomes very prerequisite for a web developer to pay special attention towards HTML, CSS and JavaScript code, concentrating more to maintain the preexisting look and feel of a web application or a website.  A web programmer has to be very careful and make sure that HTML & CSS codes written by him doesn’t create any bad effect on the parent page on a web application or website.
All this brings defensive HTML and CSS codes rendering into a limelight. Many web developers have already started practicing defensive rendering to minimize the impact of the parent page, which mainly comprises of HTML and CSS namespacing, CSS overspecifying, CSS specificity, CSS rule priorities, CSS preprocessor and more with some level of customization.
Here are some cool guidelines for defensive HTML and CSS rendering :-
Namespaces
Generally, web developers prefix Document Object Model (DOM) Level 2 HTML Specification, classes, data attributes, as well as CSS selectors with a stork to minimize the risk of conflict between the parent page and attributes.  Another trick is to prefix all of your class names and attributes with a unique name— namespace, a JavaScript code enables you to declare all global objects that can possibly conflict with code running on the parent page and prevent conflicts CSS rules.
Namespacing HTML and CSS is quite prerequisite if you’re working for any third-party application rendering directly to the publisher’s page. Make sure that all namespaced elements with namespaces have an explicit prefix and CSS selectors can easily recognize a namespaced element via its prefix. A programmer can also use the HTML namespace with CSS, especially when browsing XML with CSS. It allows you to access many useful HTML elements such as <TABLE>, <A>, <IMG>, <SCRIPT>, and <STYLE>.
CSS specificity
Namespacing your HTML and CSS is not enough to prevent  the conflict on the publisher’s page that using styles, queries, class names, CSS uses IDs, and attributes. It may result in CSS rules heavily weighed by the web browser referred to as CSS specificity. It is one popular practice used to determine the CSS rule applied by the web browsers. Inline styles, IDs, classes+attributes and elements are four key categories that define the specificity level of a CSS selector.
Overspecifying Of CSS
In the web development industry, the approach to overspecifying CSS is quite useful to stop a conflict on the publisher’s page. Overspecify the CSS rules plays great role in declaring additional selectors boosting the specificity. It prioritizes the rules whenever any web browser makes a comparison between your CSS rules against the parent page.
By using aforementioned techniques, a web programmer can easily injecting HTML and CSS codes into the publisher’s page without any conflict.

Animated Media Queries


If you apply a transition on an element for a particular supported property, and that property ever changes, it will use that transition. If a class name on that element changes and the new class changes that property, it will transition (assuming what that class does isn’t remove the transition). If JavaScript literally changes the that style property, it will transition.
Likewise, if a new media query takes affect, and that media query has something in it that changes that property on that element, it will transition. As such, there really isn’t a such thing as an “animated media query” so much as elements that just transition as expected when a new media query starts affecting the page.

Simple Example

.thing-that-moves {
  position: absolute;
  width: 100px;
  height: 100px;
  background: red;
  top: 0;
  left: 0;
  transition: left 0.5s; /* BYO prefixes */
}
@media (min-width: 400px) {
  left: 50px;
}
@media (min-width: 600px) {
  left: 100px;
}
If you were to resize your browser window across those breakpoints, you’d see a red square moving around in response.

What is the browser support?

IE 9+ on the media queries. IE 10+ on the transitions. I wouldn’t sweat the transitions as they are strictly funcandy only (if they don’t transition, it doesn’t matter, they still move). If you need deeper media query support, there is always Respond.js.

Is there any actual reason to do this?

Poops and giggles, yo. This is purely for fun. It can be a little touch just to give your site some spirit. It would be hard to make a business case, but if your performance budget doesn’t have a few bytes for funzies, I feel bad for you son.

Anything to watch out for?

If the stylesheet is parsed fast enough and the transitions get applied to an element while the page is still being laid out,those transitions might be kinda obnoxious. You might want to apply them only after the page is loaded.

How to Improve Web Navigation and Make Your Site User-Friendly


Many of the people who visit your site will do so after clicking on a search engine listing or a link on another website. This means that they may enter from a page deep within your website rather than follow the neatly laid out path from your home page to other pages of your site. By creating a user-friendly website navigation menu, you can rest assured that people will be able to find what they’re looking for, no matter what page of your site they land on.

What Is Website Navigation

Navigation is the most important element of a website. It embodies a website’s hierarchy, listing its main sections and subsections. Web navigation creates a sense of place while giving users something to hold onto. If users ever lose their way, they can look at the navigation menu to determine where they are and how to arrive at their destination.
Truthfully, people won’t use your website if they can’t find their way around it. That’s why clear, simple, and consistent web navigation is vital. Here are some guidelines for improving website navigation.

Design Multi-Level Navigation

One of the most common problems in the web design world is the failure to design good multi-level navigation. Most web designers don’t give nearly as much attention to lower-level navigation as they do to top-level navigation. This is because designing multi-level navigation is difficult considering the number of elements you have to fit into a limited amount of space on a page.
When building your website, work out its navigation from top to bottom and create sample pages for all potential levels of the site. This helps to ensure that no matter where users land on your site, they’ll be able to orient themselves and find what they’re looking for.
Create a persistent navigation menu that appears in the same place on every page, with the exception of your home page and pages where it could distract users, such as sign-up pages. A persistent navigation menu should include a link to your home page, links to the main sections and subsections of your site, and links to important “utility” pages, such as Contact Us or FAQs.

Give Every Page a Name

Every page of your site should have a name. Ideally, the page name will be placed in a prominent location, frame content that is unique to the page, and match the link the user clicked on to get to that page. If the page name isn’t obvious, users might get confused.

Use “You Are Here” Indicators

Prevent users from getting lost by highlighting their current location on the navigation menu. For example, you can use bold text or a different color to make the indicator stand out.

Use Tabs

Tabs are great for navigation menus because they’re visually distinctive and clearly divide your site into sections. Even the computer illiterate recognize tabs because they’re similar in appearance to tabs in a binder or tabs on folders in a file drawer.
A tab should already be selected when people enter your site. An active tab is typically of a different color or contrasting shade, so it looks like it’s in front of the other tabs.