About the Author:

CSS !important Rule: How to Use It Correctly

February 20th, 2018

The CSS !important rule approaches us like a fake savior angel in our darkest times while we are trying to make something work in CSS. It is a great option to have for sure, but are we really using it in the correct way and only in cases where we have no other option? In this post, we will take a detailed look at what !important rule is and how it should and shouldn’t be used by giving some explanatory examples. (more…)

About the Author:

How to Add/Remove CSS Classes Using JavaScript

January 20th, 2018

[fusion_builder_container hundred_percent=”no” hundred_percent_height=”no” hundred_percent_height_scroll=”no” hundred_percent_height_center_content=”yes” equal_height_columns=”no” menu_anchor=”” hide_on_mobile=”small-visibility,medium-visibility,large-visibility” class=”” id=”” background_color=”” background_image=”” background_position=”center center” background_repeat=”no-repeat” fade=”no” background_parallax=”none” enable_mobile=”no” parallax_speed=”0.3″ video_mp4=”” video_webm=”” video_ogv=”” video_url=”” video_aspect_ratio=”16:9″ video_loop=”yes” video_mute=”yes” video_preview_image=”” border_size=”” border_color=”” border_style=”solid” margin_top=”” margin_bottom=”” padding_top=”” padding_right=”” padding_bottom=”” padding_left=””][fusion_builder_row][fusion_builder_column type=”1_1″ layout=”1_1″ spacing=”” center_content=”no” link=”” target=”_self” min_height=”” hide_on_mobile=”small-visibility,medium-visibility,large-visibility” class=”” id=”” background_color=”” background_image=”” background_position=”left top” background_repeat=”no-repeat” hover_type=”none” border_size=”0″ border_color=”” border_style=”solid” border_position=”all” padding_top=”” padding_right=”” padding_bottom=”” padding_left=”” dimension_margin=”” animation_type=”” animation_direction=”left” animation_speed=”0.3″ animation_offset=”” last=”no”][fusion_text]This post will demonstrate two approaches for manipulating the classes of an HTML element. The first uses the plain javascript property classList and the second uses jQuery, a popular javascript library. To begin, consider the following document:

    

The document has one button with an onclick event to toggle the color of the button. The CSS defines classes to set the background color:

.blue {

 background: blue;

}

.red {

 background: red;

}

The only thing left to do is to implement the toggleColor() function in javascript.

classList

Every element has a classList property containing its class attributes. This property provides methods that make it straightforward to add or remove a class.

function toggleColor() {

 var myButtonClasses = document.getElementById("btn1").classList;


 if (myButtonClasses.contains("blue")) {

    myButtonClasses.remove("blue");

 } else {

    myButtonClasses.add("blue");

 }

 if (myButtonClasses.contains("red")) {

    myButtonClasses.remove("red");

 } else {

    myButtonClasses.add("red");

 }

}

https://codepen.io/qualitydixon/pen/GoeOOP

The above example uses three methods provided by classList.

  • contains() – Returns true if the element has the provided class, else returns false.
  • add() – Adds the given class to the element. This is ignored if the element already contains the specified class.
  • remove() – The provided class is removed from the element, if present.

An even simpler way to accomplish the same thing is to use the toggle() method. Which will add the provided class if it is not present, or remove it if it is:

function toggleColor() {

 document.getElementById("btn1").classList.toggle("blue");

 document.getElementById("btn1").classList.toggle("red");

}

https://codepen.io/qualitydixon/pen/BjbmQM

When working with multiple classes, simply comma separate the classes in separate strings:

document.getElementById("btn1").classList.toggle("blue”,  “bold");

document.getElementById("btn1").classList.toggle("red”,  “italics");

The only potential drawback to this approach is it was introduced in HTML5 and may not be supported if you are working with older browsers.

jQuery

jQuery provides methods that function almost exactly like those shown above, but you get the added bonus of using jQuery’s shorthand for selecting elements. Here is the toggleColor() function written in jQuery:

function toggleColor() {

 $("#btn1").toggleClass("blue");

 $("#btn1").toggleClass("red");  

}

https://codepen.io/qualitydixon/pen/KVEyjg?editors=1001

You could also use addClass(), removeClass(), and hasClass() to construct toggleColor() in the same manner as our first example. Note that to add multiple classes simply space separate the classes in the same string. For example:

$("#btn1").toggleClass("blue bold");

$("#btn1").toggleClass("red italics");

That’s it! Now you’re well equipped to dynamically set the appearance of DOM elements. Happy coding![/fusion_text][/fusion_builder_column][/fusion_builder_row][/fusion_builder_container]

About the Author:

3 Ways to Center in CSS

November 16th, 2016

Centering HTML elements using CSS can be a surprisingly difficult task. Getting the horizontal alignment right is relatively straightforward, but getting the vertical alignment down can prove to be challenging. And getting an element to sit smack dab in the middle of its container? Forget about it! :) I’m kidding, but how to center elements using CSS is a question I see asked pretty regularly; one for which I don’t always see good or reliable answers. So in order to provide some guidance, in this article we’ll look at 3 ways to center HTML elements using CSS. I’ll start with the most backwards compatible of the 3, then move towards what I see as the most elegant solution. Pick the one that works for you… Let’s have a look!

First, let’s see all 3 methods in one page:

See the Pen ObNRjV by Chase Allen (@ccallen001) on CodePen.

Individually,

1. Padding

The first method relies on the padding property of the containing element, and CAVEAT you have to do some calculating/experimenting with this one in order to get it right. The padding property is applied to the parent element equally all the way around on each side. Doing so forces the contained element in to the center. A good way to think about the calculations is by starting with the width and height you want for your container element (let’s say 200px for example’s sake). Next, determine the width and height you want for the centered element (let’s say 50px). You calculate the padding needed by subtracting the inner element’s dimensions from the outer’s and dividing by 2. In formulaic fashion:

padding = (outer - inner) / 2

or

p = (o - i) / 2

Using the example values from above the formula yields

75 = (200 - 50) / 2

or

75px

You set the containing element’s width and height to match the centered element’s width and height and apply apply the calculated padding. So to get a container with width and height of 200px, with a contained center element of width and height 50px… simply give the containing element a width and height equal to 50px and a padding value equal to 75px. As mentioned, this method is probably the least elegant of the three (as you have to do some calculating), but it’s probably the best supported across browsers and on older browsers as well. Here’s what the code and results look like:

See the Pen BQKRmm by Develop Intelligence (@DevelopIntelligenceBoulder) on CodePen.

2. Transform

This method relies on CSS3’s transform property. It additionally relies on the position property. This method, like method 1, is not one of great elegance; however, you won’t have to do any extra calculating or hard coding of values to get it to work. The idea with this one is to give the parent element a position of relative (setting up its child element for absolute positioning) and then using positioning on the child element to set it 50% from the top and 50% from left of the borders of the parent. Because the centered element itself has dimensions, we’ll have to pull it back a ways in order to get it to sit perfectly in the middle. We’ll use the transform: translate property to pull the element back 50% of it’s own width and height. So all together, we simply push the contained element 50% of the way from the containing element’s top and left edges… then we pull the element back by 50% of its own width and height. Doing so effectively puts the contained element dead center within the parent. Note: The transform: translate property is applied to both the X and Y axes of the child element; and a value of -50% is applied. Here’s what it looks like:

See the Pen xRVdjb by Develop Intelligence (@DevelopIntelligenceBoulder) on CodePen.

3. Flex

This last method is dirt simple and highly effective, so it’s by far the most elegant approach of the 3 discussed. This method uses flexbox. Flexbox is a relatively new concept in the world of CSS and thus has the least cross browser/older browser support. Here’s some information on flexbox browser support: https://developer.mozilla.org/en-US/docs/Web/CSS/CSS_Flexible_Box_Layout/Using_CSS_flexible_boxes#Browser_compatibility

As usual, IE is the one you have to look out for!

Using flex to center an element in its container really is as simple as giving the parent element a display value of flex, and then using the align-items and justify-content properties to center the child element(s). And the values of those two properties couldn’t be simpler either, you literally just type center for each. align-items does the vertical centering and justify-content handles the horizontal axis. The code and results look like this:

See the Pen LbNyBN by Develop Intelligence (@DevelopIntelligenceBoulder) on CodePen.

So there you have it! 3 ways to center elements using CSS. The padding method is likely the oldest and most supported approach, but you’ll need to do some calculations to get it to look just right. Using the transform property relies on CSS3 compatibility but it doesn’t require any special calculations. Using flexbox, or flex, makes the job a cinch; unfortunately, flex isn’t supported in older browsers.

Hopefully you found this article helpful. Thanks for reading!

About the Author:

How to Make Circular/Curved Text with JavaScript

September 28th, 2016

Creating circular text, or text on an curved path, in webpages may seem like somewhat of a intimidating task. There isn’t really a straightforward way to achieve it with standard HTML and CSS. There is a JavaScript plugin or two out there with some pretty decent results, but using plugins means extra dependency and load time associated tacked on to your project. So… what can you do? With a little bit of plain old vanilla JavaScript and standard CSS, it’s actually not that difficult to create curved text of your own! In this article, I’ll show you how to create circular/curved text that relies on as little as 15 lines of JavaScript. The result is functional and reusable so that you can apply as much circular text to your projects as you would like! You won’t need any special libraries or plugins of any sort; just good old fashioned HTML, CSS, and JavaScript. I’ll provide examples as we go, and I’ll provide items for consideration along the way. Circle the wagons; let’s get started!


Circular Text: The HTML

We’ll start by setting up the HTML, which is pretty much as simple as it gets. You’ll want a container for the circular text (although not 100% necessary) as well as a target element in which you’ll insert your circular text. Here’s how I’ve got it set up:

See the Pen ALoKJJ by Develop Intelligence (@DevelopIntelligenceBoulder) on CodePen.

Circular Text: The CSS

Next we’ll add a some CSS to get things set up. None of the following CSS is actually necessary, and it can be adjusted as needed. For the purposes of this tutorial, I chose a purely arbitrary blackish background with whitish text; I also chose to center the target element (the div with class=circTxt), but you can choose to position the containers and target elements however you please! Here’s how I have the CSS:

See the Pen NRvNEv by Develop Intelligence (@DevelopIntelligenceBoulder) on CodePen.

Circular Text: The JavaScript

Next comes the magic, the JavaScript. Things get a bit more complex here, but the overall logic isn’t really all that difficult. To give a broad overview before actually looking at the code, here’s what we’ll want to accomplish:

  1. Create a reusable function named circularText that takes 3 arguments: 1) the text to be written in circular fashion, 2) the radius of the circle on which the text will lie, and 3) the DOM index of the target class=circTxt element
  2. Split the text in to an array and get it’s length (i.e., the number of characters it contains)
  3. Divide the total degrees in a circle (i.e., 360 deg) by the length/number of characters in the text to determine spacing
  4. Specify the origin, or starting point, for the circular text (for simplicity’s sake, I’m going to hardcode 0 degrees)
  5. Create a loop (here using Array’s forEach method) that inserts the text around the perimeter of a circle using the defined radius and updating the origin/start value as it goes
  6. Call the function to create the circular/arced text!

Got all that? Believe me, it’s really not that complicated; less than 15 lines if you please. Here’s what the code looks like:

See the Pen rrzZoK by Develop Intelligence (@DevelopIntelligenceBoulder) on CodePen.

NOTE: I am do use ES6 syntax there (the arrow function and the template literal), but the code can easily be refactored to comply with more traditional syntax.


Well… there you have it… circular text with plain old HTML, CSS, and JavaScript!

Some things to consider are the need for adjusting the passed radius value based on how many characters are in your text. Generally speaking, the more characters you have in your text, the larger the radius you’ll need to use (however, you can create some neat effects by using a radius that might initially appear to be too small). Also note that you can created arced or curved text without going around a full circle by being purposeful about using spaces in your text.

See the Pen kkobjp by Develop Intelligence (@DevelopIntelligenceBoulder) on CodePen.

The arc effect can also be achieved by modifying the origin value used in the code (i,e., starting somewhere other than at the top of the circle). Regarding modifications to the CSS, the code could be changed to target elements with specified ids or tag names; you could use the document object’s querySelector method to achieve precision targeting as well. Additionally, you can modify both the circTxt containers (positioning them wherever you like on the page, giving them height and width, etc.) and the circular text within.

See the Pen Circular Text Generator by Chase Allen (@ccallen001) on CodePen.

I encourage you to go wild, get creative with it, circle back and have some fun! :)

About the Author:

CSS: Making the Switch from Static to Relative Units

September 22nd, 2016

CSS gives web developers plenty of options when it comes to defining lengths for HTML elements. In a broad sense, defining lengths in CSS can be broken down in to two categories: using absolute versus relative units.

Absolute units are probably most commonly done with pixel lengths with the familiar px unit. Other absolute length units exist (e.g., mm, q, cm); however, these units are far less common. You can familiarize yourself with various absolute units by clicking here.

Relative units can be a bit trickier to understand than absolute units, but their benefits are undeniable. Throughout the remainder of this article, I’ll show you some of the more common relative units in CSS and how to use them. I’ll provide some examples in order to demonstrate their behavior. As Einstein most assuredly never said, “It’s all relative, baby!” ;)

CSS Relative Units

Relative to the Parent Element

Relative to a parent element’s defined length, there’s the percentage unit (%). The percentage unit is relatively straightforward (same as percents when you learned them in school). To get an ideao fo how percentage units work, let’s say you have a parent div element that has one child div contained within it. If you set the parent div’s width to 100px, and the child div’s width to 50%, then the child div’s width will render to 50px; 50% of it’s parent div’s width. Imagine now that you have the parent div also set to 50% width (assuming that the body element is the parent of the parent div here)… with that setup, the parent div’s width will be 50% of your document’s body’s width, and the child div’s width (set to 50% as well) will be half of that. So the child will be half the width of the parent that’s half the width of the body. All of that allows for responsive web design where elements on the page will change widths (or heights or other properties) depending on the size of the browser window.

Here it is in action:

See the Pen wzqGjg by Develop Intelligence (@DevelopIntelligenceBoulder) on CodePen.

(make sure to adjust your browser/window size to see it in action).

Relative to the Browser/Window/Viewport

Relative to the size of the browser window (also known as the viewport); are viewport units (vw and vh). These relative units work similarly to percentage units; 1 v unit is equal to 1% of the viewport’s length. So if you were to assign a p element a width of 50vw, doing so would effectively set the p element’s width to half of whatever your browser window’s width is. Likewise, setting a p element’s height to 50vh would make it so that the element’s height is always 50%, or half, of your browser’s height. You can also set the width to vh and the height to vw, if you so choose. Doing so would tie an element’s width to the height of the viewport and its width to the viewport’s height. And just like with percentage units, viewport units allow for responsive web design (i.e., allowing HTML elements to respond to different devices; different screen widths and heights).

Here is an example of viewport units in action:

See the Pen ozZxdK by Develop Intelligence (@DevelopIntelligenceBoulder) on CodePen.

(make sure to adjust your browser/window/viewport size to see it in action).

Relative to Font Size

Finally, in addition to percentage units and viewport units, there are font-size relative units. These units are em, rem, ch, and ex. Em is relative to the calculated font-size of an element (typically, default is 16px). Rem refers to the font-size of a document’s root element (typically the <html> element). Ch refers to the width of the glyph 0. And ex refers to the x-height of an element’s font. Em and rem tend to be more common the ch and ex, but each have their advantages and disadvantages. Using multipliers in front of the font relative units works as you would expect (e.g., if font-size is 16px, then 2em is 32px).

Here’s an example of em and rem in action:

See the Pen pEAyKa by Develop Intelligence (@DevelopIntelligenceBoulder) on CodePen.

Conclusion

When using CSS to control the length of HTML elements, a distinction an be drawn between absolute and relative units. Relative units allow for adaptable lengths and responsive web design. Relative units can be broken down in to three unit groups: percentages, viewport, and fonts. Percentage units rely on the lengths of parent elements, viewport units rely on the dimensions of the browser window, and font relative units rely on the font size of parent or root elements.

More information about the relative units discussed here can be found on Mozilla’s Developer Network page.

About the Author:

CSS: Simple Sticky Footer

September 22nd, 2016

The sticky footer…

The oh-so-sought-after expanse at the bottom of the page that contains contact information, site navigation, a call to action, or whatever else you might want to chuck in there. It’s the element that knows its place in the world (wide web) and embraces it by staying in it’s place. A well executed sticky footer encourages your site visitors to further engage; it encourages your site’s visitors to interact with your page’s content in a familiar and enjoyable fashion.

Fortunately, creating a sticky footer isn’t really all that difficult. In the following tutorial, I’ll show you a couple quick and simple methods for making a slick looking sticky footer, one that plays well with the modern web… one that deftly displays valuable information across varying screens and multiple devices. Best of all, I’ll show you how to create your footer in a relatively simple fashion in which you won’t need to mess with unnecessary libraries, fancy plugins, or less than desirable “hacks.”

Step 1: Behavior and Positioning

First things first, you’ll want to decide how your sticky footer will be displayed; i.e., how it will behave on your page. For the purposes of this tutorial, I’ll assume there are generally two choices for you with respect to your footer’s behavior: 1) your footer can stick to the bottom of the body of your page, changing position according to your page’s body’s height, or 2) it can stick to the bottom of your browser’s window, effectively rendering the footer as an omnipresent entity on the page. Both are relatively easy to achieve and have specific advantages and disadvantages when compared to the other. Ultimately the choice is  yours.

Here’s how to stick the footer to the bottom of the body:

See the Pen EgvKKR by Develop Intelligence (@DevelopIntelligenceBoulder) on CodePen.

Things to note: 1) the body has relative positioning 2) the sticky footer has absolute positioning and a defined width 3) the bottom property for the sticky footer is set to 0.

Here’s how to stick the footer to the bottom of your browser window:

See the Pen QKrNEd by Develop Intelligence (@DevelopIntelligenceBoulder) on CodePen.

Things to note: 1) the body still has relative positioning 2) the sticky footer now has fixed positioning and a defined width 3) the bottom property for the sticky footer is still set to 0.

With both approaches, using relative units (i.e., percentage or viewport units) will allow for your footer to respond to various screen widths.

Like I said, pretty simple It really doesn’t take much more than that to create a pure CSS, simple sticky footer. But of course, we want more… Let’s take a look at getting some content in there.

Step 2: Add Some Content

So you’ve got your footer… stuck to the bottom of your page or your browser’s window… Let’s flesh it out some more with some useful information. For the purposes of this demo, I’m going to go with a mock site navigation block, a contact information block, and a call to action button.

Here’s the populated sticky footer:

See the Pen pEAyEw by Develop Intelligence (@DevelopIntelligenceBoulder) on CodePen.

Things to note here: 1) the sticky footer’s text-align property is set to center 2) div elements within the footer with display:inline-block are being used as containers 3) relative units and min- and max-widths are being used.

Aligning the text to the center and giving the containers a display of inline-block just creates a nice alignment for the content. The min and max widths further control spacing and wrap behavior; the relative units assist here as well. Next, let’s look at classing things up a bit.

Step 3: Add Some Effects

Things are looking good! You’ve got a well populated sticky footer with information balanced throughout. It’s easy to read and easy to access and it looks good across multiple browsers and multiple devices. Great! But let’s say we really want to draw in some visitors. What can we do? We can add some fancy schmancy effects to our footer, that’s what we can do! :) Let’s take a look at a few relatively simple effects that you can add to your footer in order to really draw attention to it.

If you want a relatively modest approach, there are shadow effects.

Shadow:

See the Pen bwApBw by Develop Intelligence (@DevelopIntelligenceBoulder) on CodePen.

A more modern approach may be to let the background shine through.

Transparency:

See the Pen RGkaKb by Develop Intelligence (@DevelopIntelligenceBoulder) on CodePen.

How about some interactivity?

Hover Transition:

See the Pen Xjadpq by Develop Intelligence (@DevelopIntelligenceBoulder) on CodePen.

Let’s really get their attention!

Animation:

See the Pen ozZxkO by Develop Intelligence (@DevelopIntelligenceBoulder) on CodePen.

And just to take it back to a world wide web of yesteryear…

Animated Background:

See the Pen jrLqmw by Develop Intelligence (@DevelopIntelligenceBoulder) on CodePen.

With effects, your own creativity is the limit!

Conclusion

In this tutorial, I showed you how to make a relatively simple sticky footer without needing to rely on any external libraries or unsavory methods. I showed you how to stick your footer to the bottom of your page or to the bottom or your browser’s window. I showed you how to get basic responsiveness going and how to fill your footer with content. We then looked at some neat effects that hopefully gave you some inspiration of your own. That concludes this tutorial on creating a simple sticky footer. Thanks for sticking with it!

About the Author:

CSS !important Rule: How to Use It Correctly

April 20th, 2016

The CSS !important rule approaches us like a fake savior angel in our darkest times while we are trying to make something work in CSS. It is a great option to have for sure, but are we really using it in the correct way and only in cases where we have no other option? In this post, we will take a detailed look at what !important rule is and how it should and shouldn’t be used by giving some explanatory examples.

How Cascaded Style Sheets Work

In order to understand how the !important rule works, you will first need to understand how cascaded style sheets work. As the name implies, the styles in cascaded style sheets are processed by the web browser in a certain order. The first order is based on the source of the style sheets and can be listed as the following by increasing importance:

  • 1. Browser styles. These are the default styles declared by the web browser.
  • 2. User styles. These are the custom styles the user declares using browser’s user style sheets.
  • 3. Author styles. These are the styles the developer of the website declares in CSS style sheets.
  • 4. !important author styles. Author styles with !important rules.
  • 5. !important user styles. User styles with !important rules.

In addition to the above precedence order of styles, the order of importance for the style sheets within the author styles is as follows:

  • 1. External style sheets, which are located in separate .css files.
  • 2. Internal style sheets, which are located in the same document, usually within the <head> element.
  • 3. Inline style sheets, which are applied to specific elements at the point where they appear within the HTML code.

For example, if you apply the same CSS property with different values to the same element once in the external stylesheet, once within the head element and once inline, the value of the inline style will be taken into account. As an example, let’s say that you have the following in your style.css file:

p { margin: 20px }

And the following in your HTML document:

<head>
  <style>
    p { margin: 15px }
  </style>
</head>

<p style="margin: 10px">Sample paragraph.</p>

In this case, the effective margin value for the paragraph element will be 10px, which is specified as an inline style.

In addition to these orders, specificity, a measure applied to CSS declarations to determine their weights, or importance in other words, is used in order to render the web pages properly within the browser window.

Now that we’ve seen how the cascaded style sheets work, we can continue with how the !important rule works.

How CSS !important Rule Works

As demonstrated in the above section, CSS has a natural order of importance assigned to declarations depending on where they are located. The !important statement is used for breaking this order and adding weight to a specific declaration to put it in effect, ignoring the others. It is used for overriding the styles that are previously declared in other style sources, in order to achieve a certain design or layout goal.

Explore CSS Courses

Here is a simple example:

a { color: #333 !important; }

This will render all the links on the page with #333 color regardless of what other CSS declarations are made that are affecting the link elements. As you can see from the above example, the !important keyword must be placed at the end of the declaration, after the property value and before the semicolon. In the example below, the font-size of the paragraphs is overridden by !important rule in the first declaration, even though the second declaration should have been in effect considering the natural flow of CSS.

p { font-size: 18px !important; }
#container p { font-size: 16px; }

Initially, the !important rule was introduced for use in user style sheets as a means for providing the ability to the user to modify the style of a web page to fit their needs (e.g. increase font size, make background color lighter, etc.) but eventually it became a tool that is now widely used by most CSS authors, and often times improperly. You can also check the CSS 2 specification to learn how the !important rule is defined.

Why CSS !important Should Be Used Carefully

Getting used to the !important declaration in CSS is very easy, but it is also a bad habit for a web developer since it leads to missing or ignoring the real underlying issues in the HTML structure and the corresponding CSS styles that should better be fixed in other ways. Especially in large web projects where multiple people work on the same style files, bandaging issues with the easy choice of applying !important rules will cause the issues to grow further as the development continues.

The !important rule also makes it hard for the user to apply their own styles for better readability or accessibility while viewing your website. Not only that but also the more !important rules you use, the more difficult your CSS code will become to read and maintain. For these reasons, it should be used only where it is absolutely necessary (in very few occasions) and when there is no other option. In most cases, it is possible to get rid of the need for using !important rules by simply changing the HTML tags on your page or assigning new CSS selectors to them.

Possible Good Uses of !important Rule

Custom user style sheets are the main use case for the !important rule as they let the user to modify the layout and style of the websites they are viewing to fit their needs. Most browsers allow to have user styles where you can apply your own CSS rules, sometimes with the help of browser extensions.

Another use case is when you are working with remote (third party) style files and JS scripts on your site and you need to modify the styles to suit your needs. Also, the !important rule comes in handy when overriding the style changes made by JavaScript on the fly.

It may not be considered as a must but often times, applying a different style to a smaller group of a certain class of elements will be possible with !important. For example, you have a .button class that you use on different places across your site but it is also affected by the style of certain elements containing it. In this case, applying !important to the .button class to preserve its style across different sections might be quite helpful.

One other use of !important rule is while testing your designs and while inspecting web pages using the developer tools console of the web browsers.

How to Override !important in CSS

The !important rule is used for overriding the previously assigned CSS declarations. But it is also possible to override itself. You can override the !important rule, naturally by another one. The overriding !important rule should be declared lower on the CSS flow and it should have the same or higher level of specificity in order to be in effect.

img { border: none !important; }
#article img { border: 2px solid #fff !important; }

This is how the CSS !important rule works and hopefully this post will help you in deciding where to use it and where not to use it.

Explore CSS Courses

About the Author:

CSS Class vs ID: Which One to Use

April 20th, 2016

In this post, we will take a brief look at how classes and IDs are used in CSS, and we will try to help you better understand how to decide when to use CSS class vs id by providing some simple examples.

In CSS, you can assign and control the style of HTML elements on a web page using a number of selectors. ID and class are two of the mostly used CSS selectors that not only help with building the layout of the HTML document but they also help with styling it. They are also used for controlling and manipulating the DOM elements via JavaScript but we shall leave that topic to another post.

Let’s first start with how ID and class selectors are used and then we will continue with their differences and when to use each of them.

How CSS ID Selector is Used

The id selector is used for selecting a single HTML element with a unique id attribute value. In the following example, you will see a division element <div> with an id attribute value of header.

In your stylesheet file, you can apply styles to this div element like the following:

#header { width: 100%; height: 80px; background: blue }

Note the use of # (hash) in front of the id name while applying the CSS rule. You can learn more about the id selectors on this page and this page.

How CSS Class Selector is Used

The class selector is used for selecting a single or a group of HTML elements with the same class attribute value. In the example below, you will see three paragraph elements <p> with a class attribute value of content.

This is our first paragraph.

 

This is our second paragraph.

 

This is our third paragraph.

In your stylesheet file, you can apply styles to these paragraphs like the following:

.content { margin: 20px 0; line-height: 24px; font-size: 15px }

Note the use of . (dot) in front of the class value while applying the CSS rule. You can learn more about the class selectors on this page and this page.

What’s the Difference Between CSS Class vs ID

If you noticed from the above examples, we used the id selector (#header) for a single element, whereas we used the class selector (.content) for multiple elements. This is because an id value can be given to only one HTML element, in other words, multiple elements cannot have the same id value on the same page. For example, you can have only one element with a #header id or one element with a #footer id on your page. On the other hand, a class value can be given to one or more HTML elements, usually of the same type. For example, you can have multiple paragraphs with a .content class or multiple links with a .external class.

The following example will help you better understand the difference of CSS class vs id and how to use them correctly in your layouts.

 

This is our first paragraph.

 

This is our second paragraph.

 

This is our third paragraph.

In the above HTML layout, we started with the container div. We assigned it an id (#container) because there is only one container on our page. Within this container, we have the menu (#menu) and content (#content) sections. Like the container, we have only one menu and one content section on our page. Inside the menu element, we have four links, <a>, hence we assigned a class (.link) to each of these links. Similarly, we assigned a class (.text) to each of the paragraphs in the content div.

If we were to apply styles to these elements, we would use something like the following:

#container { width: 1080px; margin: 0 auto; background: #eee }

#menu { height: 90px; background: #ddd }
.link { color: #000; text-decoration: none }

#content { padding: 20px }
.text { font-size: 15px }

When to Use Class vs ID in CSS

The basic rule that you need to keep in mind while using classes and ids in CSS is that, id is used for single elements that appear on the page for only once (e.g. header, footer, menu), whereas class is used for single or multiple elements that appear on the page for once or more than once (e.g. paragraphs, links, buttons, input boxes). While you can also use a class for a single element, in order to get used to this distinction and use these separators as they are intended, it is better to make a habit of using classes to control the style of multiple of the same type of element.

Another point to keep in mind is that an HTML element can have both an id and a class. For example, let’s say you need to have two boxes on your page with the same size and style but different positioning. In this case, you can assign the same class to these boxes to control their size and style and then assign a different id to each box to control their positions.

 

Elements may also be assigned multiple classes at the same time. This is especially helpful when you need to style a smaller group of elements within a certain type of element on your page. For example, let’s say you have a .content class that is applied to all paragraphs. If you want to add a border or any other style to certain paragraphs, you can add another class such as .bordered, like the following:

This paragraph has no borders.

 

This paragraph has borders.

Note the empty space between the two class names in the class attribute of the second paragraph. A sample CSS for the above HTML code would be:

.content { margin: 10px; font-size: 15px; color: blue }
.bordered { border: 2px solid #222 }

It is important to use the IDs and classes correctly based on the above points because their wrong use may result in non-functional HTML code and even if the page may look good on a certain browser or device, it may look broken on another one.

This concludes our discussion about CSS class vs id and we hope that you found it to be helpful.

About the Author:

5 Examples to Help You Understand How CSS Opacity Works

April 20th, 2016

You can control the transparency of HTML elements on a web page such as text, images or backgrounds with the help of the opacity property in CSS. In this tutorial, we will talk about CSS opacity and we will provide some examples to demonstrate how it works.

How CSS Opacity Works

The word opaque is used for describing objects that are fully visible, i.e. with no transparency. On a web page, a fully opaque element has an opacity value of 1 and a fully transparent element has an opacity value of 0. By default, all elements have an opacity value of 1. From 0 to 1, the opacity property controls the transparency level of the element. For example, the following code will make the div elements half transparent.

div { opacity: 0.5 }

An element with 0 opacity will be totally invisible; it will still occupy its physical space on the page but it won’t be visible. Hence, if you want to make an element invisible, you can use the opacity property, as well as the visibility property in CSS.

CSS opacity was introduced with CSS 3 and it has nice support among all major web browsers as of now. If your project requires you to support Internet Explorer 8 or older versions, you will need to also use the MS alpha filter property like the following:

div {
  opacity: 0.5;
  filter: alpha(opacity=50);
}

Note that while the opacity can have decimal values between 0 and 1, the alpha filter’s opacity values can range from 0% to 100%.

You can read further technical details and the specification of the CSS opacity property on the following links:

CSS Color Module Level 3 – Transparency / Opacity
MDN – CSS Opacity

Controlling the Opacity of Parent and Child Elements

Opacity is applied to the whole element uniformly. The child elements are also affected from the opacity value of their parent. You can apply different opacity levels to parent and child elements to achieve different levels of transparency like the following:

#parent { opacity: 0.8 }
#child { opacity: 0.5 }

The following examples will demonstrate how child elements are affected by their parents’ opacity:

CSS Opacity - 1

In the first example above, both boxes have their opacity set to 1. In the second example, the parent box (black) has an opacity of 0.8 and the child (orange) has an opacity of 1. In the third example, the parent has an opacity of 0.8 and the child has an opacity of 0.5. Note the difference in the color tone (transparency) of the orange box across three examples.

Using CSS Opacity to Create Transparent Images

You can easily add a transparency effect to your images using the CSS opacity property. Let’s assume that we are displaying the same image two times on our page. The following code will make the second image transparent:

#img1 { opacity: 1 }
#img2 { opacity: 0.6 }

The result will be something like the following:

CSS Opacity - 2

Changing Opacity on Hover

Following the above example of a transparent image, you can also control the transparency of images or other HTML elements on hover by changing their opacity. The following code will make the image transparent when you bring the mouse cursor on it.

#img1 { opacity: 1 }
#img1:hover { opacity: 0.6 }

Using CSS Opacity for Backgrounds

You can assign opacity to backgrounds in two ways. In the first way, you specify a value for the opacity property as you saw in the examples we worked on so far.

div {
  opacity: 0.5;
}

In the second way, you specify the alpha channel value in the RGBA (Red, Green, Blue, Alpha) declaration of the background color like the following:

div {
  background: rgba(0, 0, 0, 0.5);
}

By changing the R, G and B values, you can have a transparent background of any color. This is also how you can have non-transparent child elements inside a transparent element. Normally, the opacity value of the parent will descend to its child elements; however, by using a transparent background, you can leave the child elements to be opaque while keeping their container transparent.

Transparent Borders with CSS

If you are making use of large borders in your design and you need to apply opacity to them, you can assign an alpha channel value to the border color as shown in the following example:

.image-box {
  border: 15px solid rgba(0, 0, 0, 0.5);
}

This concludes our discussion about the opacity property. We provided various examples for different use cases and we hope that they will help you better understand how CSS opacity works.

About the Author:

Simple CSS z-index Tutorial for Beginners

April 20th, 2016

In this tutorial, we will talk in detail about what CSS z-index property is, how it works, its default value and the values it can have by giving some examples. We will also mention some use cases to give you ideas about where you can apply z-index in your web layouts.

What is CSS z-index?

Even though web pages are displayed on two-dimensional screens, a web page actually has three dimensions: X, Y and Z. X is the horizontal dimension which expands from the left of the screen to the right, Y is the vertical dimension from the top of the screen to the bottom, and Z is the depth dimension which you can think of it like the direction of an imaginary perpendicular line that is drawn from the screen surface to your eyes, going up towards your eyes and down behind the page.

Z axis, the depth of the page in other words, allows the placement and positioning of the web page elements in a stacking order, or layers. In the natural flow of an HTML document, the elements do not overlap, they are contained within their own space that doesn’t interfere with the space of other elements. However, using CSS techniques such as the position and z-index properties, the elements can be easily positioned and overlapped to achieve the design and functionality goals.

The CSS z-index property controls how the HTML elements stack on the Z axis of a web page. It allows you to position and display an element on top of the other elements or move an element behind the others. The z-index property is especially useful when you want to change the display order of overlapping elements that have absolute or fixed positions.

The following sample CSS rule assigns a z-index value of 1 to a navigation bar with fixed position:

#navbar { position: fixed; z-index: 1 }

z-index was introduced in CSS 2 and it has nice support across all modern web browsers. You can also check the z-index definition on W3.org if you would like to read more about it.

How Does CSS z-index Property Work

Web page elements have a natural stacking order by default. The z-index property intervenes with this order by specifying which elements will be displayed on top of the other elements in the Z axis. z-index property works on positioned elements, i.e. elements that have relative, absolute or fixed positioning. A greater z-index value means that the element will be in front of the other one and it can be said that it will be displayed closer to the viewer. The following is a basic example for two overlapping boxes with different z-index values:

.box { position: absolute; width:150px; height: 150px }
.black { background: #000; top: 0; left: 0; z-index: 2 }
.gray { background: #999 top: 75px; left: 75px; z-index: 1 }

When you assign a z-index value to an element, all its descendants (its child elements) will have the same stacking order as their parent element in the flow of the page. What this means is that if you place another box inside the gray box and give it a z-index value of 3, it will not be displayed above the black box because its parent (gray box) has a stacking order of 1 which is less than 2 of the black box.

.box { position: absolute; width:150px; height: 150px }
.black { background: #000; top: 0; left: 0; z-index: 2 }
.gray { background: #999 top: 75px; left: 75px; z-index: 1 }
.box-blue { position: relative; width:50px; height: 50px; background: blue; top: 125px; left: 125px; z-index: 3 }

The z-index value must be an integer and it can have positive or negative values. Elements with positive z-index will be displayed on top of the elements with no z-index; similarly, elements with negative z-index will be displayed behind the elements with no z-index. If you give the same z-index value to different elements that don’t have parent-child relationship, they will be displayed based on their appearance order in the page structure.

The Default z-index Value of HTML Elements

The default z-index value of all the elements on a web page is auto, which corresponds to 0 where no z-index is assigned. An element with z-index: -1 will be displayed behind all other elements on the page, assuming they are given no z-index values. If the z-index is not defined for a child element, its default z-index value will be auto, which means that each child of a parent element will automatically have the stack order of its parent and will be displayed accordingly.

What Values Can CSS z-index Have?

z-index allows you to display HTML elements in a relative order on the Z axis of the page. Therefore, there is no absolute start or end values you should be paying attention to (except integer value limits). For example, you can give a z-index value of 100 to an element and a z-index value of 200 to another element, or a z-index value of -15 to another one. The important point here is that z-index is a way for assigning stacking order to elements relative to each other.

z-index property can have the following values:

  • auto – The default value.
  • number – Integer value, can be positive or negative.
  • initial – The initial value.
  • inherit – The parent element’s value.

Where to Use CSS z-index

You can use the CSS z-index property in a number of cases depending on your specific needs on your website or web application. For example you can use it for overlapping images in a photo gallery, you can use it on a tooltip or a popup window that appears when you hover over or click on an element. You can use it on navigation bars and dropdown menus which should be visible at all times, above other sections of the page. Image maps, layered layouts, social sharing buttons are some of the other possible uses of the CSS z-index property.

This was a brief introduction to z-index and we hope that it will be helpful while using this CSS property in your projects.