RSS

Category Archives: HTML

How to Make Mobile Friendly Websites. Responsive Web Design for Beginners

Responsive Web Design is a web design process which ensures optimal viewing experience in all displays available. The display can be of desktops, tablets, mobiles and now the increasingly popular big screens of smart televisions.
This article helps you to make your website mobile friendly or tablet friendly. This article suits for those developers who wish to convert their existing website to responsive layout or for those who wish to develop a responsive website from scratch.

Here I have listed few techniques which help you to make your website responsive. For better understanding, I have created 2 demo pages. One is not responsive and other one is responsive. I will be using these pages to illustrate each points. Here is the html which I have used for both responsive and non responsive pages.

Demo 1: Non Responsive Web Page
Demo 2: Responsive Web Page

 

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
<div class=”container”><!– Main Container –>
    <div class=”header”><!– Top Header –>
        <div class=”logo-wrapper”><!– Top left for logo –>
            <img class=”logo”/>
        </div>
        <div class=”search-wrapper”><!– Top right for search –>
            <input type=”text” class=”search”/>
        </div>
    </div>
    <div class=”main”><!– Main content holder –>
        <div class=”content-wrapper”><!– Main window for content –>
            <h1 class=”title”></h1>
            <div class=”content”></div>
        </div>
        <div class=”sidebar-wrapper”><!– Right sidebar –>
            <ul class=”widget-wrapper”>
                <li class=”widget”><!– First widget –>
                    <div class=”widget-title”></div>
                    <div class=”widget-content”></div>
                </li>
                <li class=”widget”><!– Second widget –>
                    <div class=”widget-title”></div>
                    <div class=”widget-content”></div>
                </li>
                <li class=”widget”><!– Third widget –>
                    <div class=”widget-title”></div>
                    <div class=”widget-content”></div>
                </li>
            </ul>
        </div>
    </div>
    <div class=”footer”></div>
</div>

 

Fluid Grids

While implementing your design from Photoshop files using html, try to avoid tables for layouts. Using tables give a less flexible layout. Use tables only for its real purpose, i.e. to display tabular data. For layout design, use div tags instead. div tags are by default block level elements. They can be floated based on our layout and will stack smoothly in small display sizes. As the term suggests, fluid grids means the grid is self adjustable. A fixed grid is defined using pixels or points, where as the width of fluid grid is defined using percentages or Ems. When we use say 90% width for the main page container div tag, the div itself will shrink when we reduce the size of screen or browser.

In the non-responsive page design demo, we have created a main parent div of 960px width and all inner sections are clearly defined using pixels. While in responsive page, we gave 68% width to main content area and 32% width for sidebar.

CSS3 Media Queries

CSS3 media queries allow a developer to set css style rules based on different display properties. The size of a mobile device may be different from that of a tablet. We use media queries to show a web page comfortably in each devices.

In our demo, we have used media queries to display all major blocks, one below the other. This layout is more comfortable for mobile users to read an article. Some websites hide some elements in smaller display devices. This helps to avoid distractions like ads or less important content.

Fluid Image size

This part is simple, yet really powerful for responsive web design. Usually we design needed image with a size which is predefined for the layout. Only thing we need to add is a width measurement in percentage. This will increase or decrease image size based on screen width.

Advertisements
 
6 Comments

Posted by on September 13, 2013 in CSS, HTML

 

3D Button Parallax

The introduction of CSS3 resulted in the explosion of beautiful and interesting buttons, styled with gradients, shadows, and borders – often to achieve a 3D effect. The problem with such 3D buttons is a static perspective. The 3D is not always very convincing when you can only see its front and perhaps a bit from an edge or two – even when the page moves and the position of the button on the page moves.

Fortunately, we can achieve a realistic perspective effect with the help of 3D transforms to adjust the sides of the buttons. We can do this without modifying existing HTML, by using pseudo elements for the sides. Then bring forward the button itself withtranslateZ.

Before we start, we must first solve a problem. The perspective origin point is usually set at the vertical and horizontal center of the element. This means that when we set it based on the body we will get something like this:

By setting the height of the body to be 100%, we can fix the perspective origin point to the center of the viewport like this:

html {
  height: 100%;
  overflow: hidden;
}

body {
  height: 100%;
  overflow-y: scroll;
}

For a simple <button>, here’s the CSS:

button {
  position: relative;
  display: inline-block;
  padding: 4px 16px;
  border: 0;
  background-color: blue;
  background-image: radial-gradient(ellipse at top, rgba(255, 255, 255, 0.15) 50%, transparent);
  color: #222;
  transform-style: preserve-3d;
  transform: translateZ(20px);
}

button::before {
  content: "";
  position: absolute;
  width: 100%;
  height: 100%;
  left: 0;
  top: 0;
  transform-origin: 0% 0%;
  transform: rotateX(-90deg);
}

button::after {
  content: "";
  position: absolute;
  width: 100%;
  height: 100%;
  left: 0;
  top: 0;
  transform-origin: 0% 0%;
  transform: rotateY(90deg);
}

But how do we get 4 sides for each button with just 2 pseudo elements? JavaScript! if we want to avoid adding extra wrappers to each button (we do) we need scripting to move the top side down and the left side to the right depending on where the button is relative to the user’s viewport. The script for switching the top with the bottom side of the button is pretty straightforward – changing top/bottom or right/lest sides occurs only on load and on resize, and top/bottom only on scroll:

$(window).on("load resize", function() {
  topHalf();
  leftHalf();
});

$("body").scroll(function() {
  topHalf();
});

function topHalf() {
  $("button").each(function() {
    var self = $(this),
        offTop = self.offset().top,
        scrTop = $(window).scrollTop(),
        halfWindowHeight = ($(window).height())/2;

    self.toggleClass("top-half", (offTop - scrTop) < halfWindowHeight);
  });
}

function leftHalf() {
  $("button").each(function() {
    var self = $(this),
        offLeft = self.offset().left,
        halfWindowWidth = ($(window).width())/2;

    self.toggleClass("left-half", offLeft < halfWindowWidth);
  });
}

Editor’s note: This could certainly be refactored a bit to lend structure and gain some efficiency. Feel free to fork the Pen below and have a go!

Some new classes will help position the sides:

button.top-half::before {
  top: auto;
  bottom: 0;
  transform-origin: 100% 100%;
  transform: rotateX(90deg);
}

button.left-half::after {
  left: auto;
  right: 0;
  transform-origin: 100% 100%;
  transform: rotateY(-90deg);
}

Keep in mind that if you use classes to float the buttons (for example .pull-left and.pull-right like in Twitter Bootstrap) you will know where each button is positioned horizontally and thus be able to skip half of the JavaScript code.

Here’s a styled demo to play around with. It has an animated push-down effect for the buttons and includes some other 3D elements that don’t requre any JavaScript:

A similar technique can also be used to replicate the 3D Inset Parallax Effect in a very rough way. It’s a bit more complex, but doesn’t require any JavaScript:

 
4 Comments

Posted by on September 8, 2013 in CSS, HTML

 

The HTML5 progress Element

Here is the basic markup for the progress element:

<progress></progress>

As per the standard defined by W3C, the progress element represents the completion progress of a task. A progress element must have both a start tag (i.e. <progress>) and an end tag (i.e. </progress>), even though it looks like a replaced element (like an input). This is good though, as it helps with fallback content as we’ll cover later.

Apart from the global attributes, it can have two more attributes:

  • max – Indicates how much task needs to be done before it can be considered as complete. If not specified the default value is 1.0.
  • value – Indicates the current status of the progress bar. It must be greater than or equal to 0.0 and less than or equal to 1.0 or the value of the max attribute (if present).

States of progress bar

A progress bar can be in two states – indeterminate and determinate.

1. Indeterminate

Indeterminate state of the progress bar in Chrome 29 on Mac OS 10.8

Based on your combination of browser and operating system, the progress bar can look different. Zoltan “Du Lac” Hawryluk covers the cross browser behavior of progress element in great depth in his article on HTML5 progress bars (which is definitely worth reading). Wufoo has some screenshots of how it looks on other operating systems on their support page for progress.

It’s pretty easy to target and style an indeterminate progress bar because we know that it doesn’t contain the value attribute. We can make use of CSS negation clause :not() to style it:

progress:not([value]) {
   /* Styling here */
}

2. Determinate

Throughout this article, we’ll only focus on styling the determinate state of the progress bar. So let’s change the state by adding the max and value attribute.

<progress max="100" value="80"></progress>

Without applying any CSS, the progress bar looks like this in Chrome 29 on Mac OS 10.8.

Determinate state of the progress bar in Chrome 29 on Mac OS 10.8
Note that only adding the max attribute doesn’t change the state of the progress bar because the browser still doesn’t know what value to represent.

This is pretty much all that we can do in HTML as rest of the work is done by CSS. At this stage let’s not worry about the fallback techniques for supporting older browsers that don’t understand the progress element.

Styling progress bars

We can target determinate progress bars using the progress[value] selector. Usingprogress only is fine as long as you know that you do not have any indeterminate progress bars in your markup. I tend to use the former because it provides clear distinction between the two states. Just like any other element we can add dimensions to our progress bar using width and height:

progress[value] {
  width: 250px;
  height: 20px;
}

This is where the fun part ends and things get complicated because each category of browsers provide separate pseudo classes to style the progress bar. To simplify things, we don’t really care about which versions of each browser support the progress element, because our fallback technique will take care of the rest. We classify them as follows:

  • WebKit/Blink Browsers
  • Firefox
  • Internet Explorer

WebKit/Blink (Chrome/Safari/Opera)

Google Chrome, Apple Safari and the latest version of Opera (16+) falls into this category. It is evident from the user agent stylesheet of webkit browsers, that they rely on -webkit-appearance: progress-bar to style the appearance of progress element.

User-agent stylesheet of webkit browsers

To reset the default styles, we simply set -webkit-appearance to none.

progress[value] {
  /* Reset the default appearance */
  -webkit-appearance: none;
   appearance: none;

  width: 250px;
  height: 20px;
}
Progress bar appearance after reset

On further inspecting the progress element in Chrome Developer Tools, we can see how the spec is implemented.

Chrome Developer Tools Snapshot

WebKit/Blink provides two pseudo classes to style the progress element:

  • -webkit-progress-bar is the pseudo class that can be used to style the progress element container. In this demo we’ll change the background color, border-radius and then apply inset box shadow to the progress element container.
  • -webkit-progress-value is the pseudo class to style the value inside the progress bar. The background-color of this element by default is green which can be verified by inspecting the user-agent stylesheet. For this demo we will create a candystrip effect using linear-gradient on background-image property.

First we’ll style the -webkit-progress-bar (the container):

progress[value]::-webkit-progress-bar {
  background-color: #eee;
  border-radius: 2px;
  box-shadow: 0 2px 5px rgba(0, 0, 0, 0.25) inset;
}
Styling progress bar container

Next we’ll style the -webkit-progress-value (the bar) with multiple gradient backgrounds. One for striping, one for top to bottom shadowing, and one for left to right color variation. We’ll use the -webkit- prefix for the gradients since we’re using it for the progress bar itself anyway.

progress[value]::-webkit-progress-value {
  background-image:
	   -webkit-linear-gradient(-45deg, 
	                           transparent 33%, rgba(0, 0, 0, .1) 33%, 
	                           rgba(0,0, 0, .1) 66%, transparent 66%),
	   -webkit-linear-gradient(top, 
	                           rgba(255, 255, 255, .25), 
	                           rgba(0, 0, 0, .25)),
	   -webkit-linear-gradient(left, #09c, #f44);

    border-radius: 2px; 
    background-size: 35px 20px, 100% 100%, 100% 100%;
}
Styling progress bar value

Adding Animation

At the time of writing only WebKit/Blink browsers support animations on progress element. We’ll animate the stripes on -webkit-progress-value by changing the background position.

@-webkit-keyframes animate-stripes {
   100% { background-position: -100px 0px; }
}

@keyframes animate-stripes {
   100% { background-position: -100px 0px; }
}

And use this animation on the -webkit-progress-value selector itself.

-webkit-animation: animate-stripes 5s linear infinite;
        animation: animate-stripes 5s linear infinite;

Pseudo Elements

At the time of writing only WebKit/Blink browsers support pseudo elements ::beforeand ::after on progress bar. By simply looking at the progress bar, it is not possible to tell the actual value. We can solve this problem by displaying the actual value right at the tail-end of the progress bar using either ::before or ::after.

progress[value]::-webkit-progress-value::before {
  content: '80%';
  position: absolute;
  right: 0;
  top: -125%;
}
Pseudo elements in action

Interestingly, content: attr(value) doesn’t work on progress bars. However, if you explicitly specify the text inside the content attribute, it works! I haven’t been able to find out the reason behind this behavior. Since this works only on WebKit/Blink browsers, there is no good reason to embed content inside pseudo elements, at least for now.

Similarly, ::after is used to create nice little hinge effect at the end of the progress bar. These techniques are experimental and not really recommended to be used if you are aiming for cross-browser consistency.

progress[value]::-webkit-progress-value::after {
  content: '';
  width: 6px;
  height: 6px;
  position: absolute;
  border-radius: 100%;
  right: 7px;
  top: 7px;
  background-color: white;
}

2. Firefox

Similar to WebKit/Blink, Firefox also uses -moz-appearence: progressbar to paint the progress element.

Firebug screenshot

By using appearence: none we can get rid of the default bevel and emboss. This unfortunately leaves behind a faint border in Firefox which can be removed by usingborder: none. This also solves the border issue with Opera 12.

progress[value] {
  /* Reset the default appearance */
  -webkit-appearance: none;
     -moz-appearance: none;
          appearance: none;

  /* Get rid of default border in Firefox. */
  border: none;

  /* Dimensions */
  width: 250px;
  height: 20px;
}
Faint border in Firefox and Opera

Firefox provides a single pseudo class (-moz-progress-bar) we can use to target the progress bar value. This means that we cannot style the background of the container in Firefox.

progress[value]::-moz-progress-bar { 
  background-image:
    -moz-linear-gradient(
      135deg, 
      transparent 33%, 
      rgba(0, 0, 0, 0.1) 33%, 
      rgba(0, 0, 0, 0.1) 66%, 
      transparent 66% 
    ),
    -moz-linear-gradient(
      top, 
      rgba(255, 255, 255, 0.25), 
      rgba(0, 0, 0, 0.25)
    ),
    -moz-linear-gradient(
      left, 
      #09c, 
      #f44
    );

  border-radius: 2px; 
  background-size: 35px 20px, 100% 100%, 100% 100%; 
}

Firefox doesn’t support ::before or ::after pseudo classes on progress bar, nor does it allow CSS3 keyframe animation on progress bar, which gives us a slightly reduced experience.

3. Internet Explorer

Only IE 10+ natively supports progress bar, and only partially. It only allows changing the color of the progress bar value. IE implements value of the progress bar as the colorattribute rather than the background-color.

progress[value]  {
  /* Reset the default appearance */
  -webkit-appearance: none;
     -moz-appearance: none;
          appearance: none;

  /* Get rid of default border in Firefox. */
  border: none;

  /* Dimensions */
  width: 250px;
  height: 20px;

  /* For IE10 */
  color: blue; 
}

What about browsers that don’t support them?

The progress element is natively supported in: Firefox 16+, Opera 11+, Chrome, Safari 6+IE10+ is partially supports them. If you want to support older browsers, you’ve got two options.

1. Lea Verou’s HTML5 progress polyfill

Lea Verou’s excellent polyfill adds almost full support for Firefox 3.5-5, Opera 10.5-10.63, IE9-10. This also adds partial support in IE8. It involves including progress-polyfill.js file in your HTML and adding CSS selectors that the script file uses. To know more about its usage, check out the CSS source code of the project page.

2. HTML fallback

This is my preferred (no-js) approach. It makes use of a common technique that is also used by audio and video elements.

<progress max="100" value="80">
    <div class="progress-bar">
        <span style="width: 80%;">Progress: 80%</span>
    </div>
</progress>

Simulate the look and feel of progress bar using div and span inside the progress tag. Modern browsers will ignore the content inside the progress tag. Older browsers that cannot identify progress element will ignore the tag and render the markup inside it.

.progress-bar {
  background-color: whiteSmoke;
  border-radius: 2px;
  box-shadow: 0 2px 3px rgba(0, 0, 0, 0.25) inset;

  width: 250px;
  height: 20px;

  position: relative;
  display: block;
}

.progress-bar > span {
  background-color: blue;
  border-radius: 2px;

  display: block;
  text-indent: -9999px;
}

It is fairly common to use both the techniques in conjunction and it is perfectly safe for production sites. Once you get hold of styling a single progress bar, then adding styles for multiple progress bars is merely an exercise which can be accomplished using classes.

The demo should run fine for all the browsers including Internet Explorer (down to IE 8). The progress bar color is blue in all the versions of Internet Explorer. Opera 11 and 12 doesn’t permit changing the progress bar color. Hence, it shows the default green color. The demo uses additional markup to display some meta information about the progress bar and the percentage value.

For additional reading, check out the HTML5 Doctor article. It covers some similar ground but has some bits about a few additional attributes as well as how to update the bar with JavaScript if you need that.

 
8 Comments

Posted by on September 8, 2013 in HTML

 

Store HTML View File In A Variable

In this tutorial we are going to re-create this functionality and send variables that can be used in a HTML file. We will also be able to return the contents of that HTML inside a variable to output this in any place we want within our application.

To achieve this we are going to use the PHP output controller functions.

View File

A typical view file should content just the HTML for the page, this file should only be used to output contents to the visitor, there should not be any logic in the View. All the logic in your application should be done in the controller and this will be sent to the view.

Below is a simple example of a view file it contains the title and the content of the page.

<div>
    <h1><?php echo $title; ?></h1>

    <p><?php echo $content; ?></p>
</div>

Calling View File

When we are calling our view file we are first going to create an array of variables that can be passed to our view.

The key of these array values will be turned into variable names in our view. As we only had a title and content variables we can just pass these into our getView() function.

The getView() function takes two parameters, first will be the location of our view file, the second will be the variables sent to the view file.

<?php
    $vars = array();
    $vars['title'] = 'Page Title';
    $vars['content'] = 'This is an example of displaying content in the view file';

    return $this->getView('view_file.php', $vars);
?>

Get View Function

Creating the method to get the view files and return it’s content is made easy by using theoutput control functions built into PHP.

First we start off by making sure that the view file exists, if the view file doesn’t exist then we can’t continue with the function so we just return false at that stage.

Next we can take the array of variables and use the extract() function that will turn the array keys into variables.

// Extract the variables to be used by the view
if(!is_null($vars))
{
    extract($vars);
}

We need to include the view file into the script so we can use these variables but as we want to return the content of the view file we need to stop PHP from outputting the content of the file, to do this we start the output buffer using ob_start().

ob_start();

With the output buffer started we include the view file, which means it will have access to the variables we have created using the extract() function.

include_once $viewFile;

The view file is not output because we started the ob_start(), to get the content of what is in the buffer we need to use another output control function ob_get_contents(). This will get what would be output and return the contents of the output buffer.

$view = ob_get_contents();

As we have collected all the output and don’t want anything else included in the output of the view file then we need to stop the output buffer by using the function ob_end_clean().

Finally we can return the contents of the view file with the HTML populated with the variables we sent to it.

Below is full getView() method.

<?php
/**
* Get the view file
*/
public function getView($viewFile, $vars = NULL)
{
    // Check the view file exists
    if(!file_exists($viewFile))
    {
         return false;
    }

    // Extract the variables to be used by the view
    if(!is_null($vars))
    {
        extract($vars);
    }

    ob_start();

    include_once $viewFile;

    $view = ob_get_contents();

    ob_end_clean();

    return $view;
}
?>

 

 
6 Comments

Posted by on September 5, 2013 in HTML