Tuesday, August 16, 2016

Revisiting the CSS Background Property_part1

In this tutorial we’re going to look into one of the older, more familiar CSS properties: backgroundbackground is one of several CSS properties whose features are often overlooked. In fact, it saw an upgrade with CSS3, receiving new capabilities beyond just adding a background image or color. Let’s look into some of them!

1. Background Position Offset

Positioning a background graphic is straightforward and something you’re likely familiar with already. If we want to position the background to the bottom right of the element, we apply bottom right to background-position. For example:
  1. #workspace {
  2.     width: 100%;
  3.     max-width: 668px;
  4.     height: 400px;
  5.     background-color: #525d62;
  6.     background-image: url(images/macbook.png);
  7.     background-repeat: no-repeat;
  8.     background-position: right bottom;
  9. }
Or, with the shorthand, background, after the url definition:
  1. #workspace {
  2.     width: 100%;
  3.     max-width: 668px;
  4.     height: 400px;
  5.     background: #525d62 url(images/macbook.png) no-repeat right bottom;
  6. }
Since the advent of CSS3 we’ve been able to specify the position offset; the precise distances to the positions set. Taking our example of bottom right, we include bottom 20px right 30px to position our background at 20px from the bottom and 30px from the left.
  1. #workspace {
  2.     width: 100%;
  3.     max-width: 668px;
  4.     height: 400px;
  5.     background-color: #525d62;
  6.     background-image: url(images/macbook.png);
  7.     background-repeat: no-repeat;
  8.     background-position: right 30px bottom 20px;
  9. }
The positions (bottomtoprightleft) can be defined in any order, but the offset length must be defined after each background position.




Credit goes to Metin Kazan for the illustrations.

2. Multiple Background Images

The background property also allows us to add multiple background images. Therefore, let's extend our previous example with more stuff and gadgets.




We add these images to a single background or background-image declaration by separating each one with a comma. We use the background-position property, which also accepts multiple values, to control each of those background images.
  1. #workspace {
  2.     height: 400px;
  3.     background-color: #525d62;
  4.     background-image: 
  5.         url(images/macbook.png),
  6.         url(images/mouse.png),
  7.         url(images/hdd.png),
  8.         url(images/phone.png),
  9.         url(images/ipad.png),
  10.         url(images/coffee.png),
  11.         url(images/camera.png);
  12.     background-repeat: no-repeat;
  13.     background-position: 
  14.             50% 50%,   /* macbook.png */
  15.             75% 295px, /* mouse.png */
  16.             75% 230px, /* hdd.png */
  17.             96% 240px, /* phone.png */
  18.             20% 250px, /* ipad.png */
  19.             22% 190px, /* coffee.png */
  20.             7% 280px; /* camera.png */
  21. }
We can use fixed units (such as pixels), flexible units (such as percentages), or a combination of the two.

Each pair of values represents coordinates from the top left of the container element, to the top left of the image. For example, the top left of the camera image is 280px from the top of the container, then 7% of the available width across from the left.


Note: The available width is the total width of the container element, minus the width of the background image. Therefore a background image positioned 50% along the x axis appears exactly centered!

(Continue)
If you found this post interesting, follow and support us.
Suggest for you:

CSS: Foundation classes on CSS

CSS Animations: Create Amazing Effects on Your Website

Coding Made Easy: HTML & CSS For Beginners

Bootstrap 4 Rapid web development framework HTML CSS JS

Saturday, August 13, 2016

Quick Tip: Using CSS Counters to Style Incremental Elements

In this quick tip, we’ll cover the very basics of CSS counters; a useful, yet not so well-known CSS feature. When we’re done building our demo, we’ll take a look at some real world examples of sites which take advantage of CSS counters.

The Goal: Styling an Ordered List
  As a first step, let’s look at the layout we’ll be building:


Nothing fancy, right? Here’s the challenge though: we’ll be using semantic markup, avoiding the temptation to use unnecessary div and span elements to build those counter markers.

Let’s discuss a clean and flexible solution!

CSS Counters

All it takes to generate the aforementioned layout is to define an ordered list. At this point, you might be wondering if we could have used another element or even an unordered list. The short answer is “yes”, but keep in mind that an ordered list is the only element that accurately describes the structure of our page.

You’ll then likely ask if it’s possible to fully customize the appearance of the ordered list numbers, building the desired layout that way. Styling the ordered list numbers would be really tricky. Thankfully though, there’s an alternative cross-browser approach, so let’s hide the default list numbers and take advantage of CSS counters instead.

Syntax
CSS counters allow us to generate numbers based on repeated elements, and style them accordingly. Think of CSS counters as variables whose values can be incremented. Let’s look at the basic syntax:
Create a new counter
Here we create a new counter on an ordered list and define its scope. We use the counter-reset property.

The first value is the counter’s name
followed by an optional parameter which defines the starting value of the counter (default: 0). Note that the counter will always start counting upwards, so the first generated value in our case will be 1.
Styling the child element
In this second diagram we can see that we’re styling the ::before pseudo-element of the li on our list.
  1. Here we’ve added the counter’s value to the content of our ::before. It’s worth mentioning that by using CSS counters with the content property, we’re able to concatenate (join) the generated numbers with strings.
  2. We refer to our counter’s name
  3. and define the counter’s style as being “decimal”. The possible values here are similar to those used for the list-style-type property.
  4. In the counter-increment rule we again refer to our counter’s name
  5. then use an optional parameter to indicate by how much the counter is incremented. The default value here is 1.
Markup
Based on what we’ve just discussed, here’s our markup:
  1. <ol>
  2.   <li>
  3.     <h4>List Item</h4>
  4.     <p>Some text here.</p>
  5.   </li>
  6.   <li>
  7.     <h4>List Item</h4>
  8.     <p>Some text here.</p>
  9.   </li>
  10.        
  11.   <-- more list items here -->
  12. </ol>
And the related CSS:
  1. ol {
  2.   counter-reset: section;
  3. }
  4.  
  5. li { 
  6.   list-style-type: none;
  7.   font-size: 1.5rem;
  8.   padding: 30px;
  9.   margin-bottom: 15px;
  10.   background: #0e0fee;
  11.   color: #fff;
  12. }
  13.  
  14. li::before {
  15.   content: counter(section);
  16.   counter-increment: section;
  17.   display: inline-block;
  18.   position: absolute;
  19.   left: -75px;
  20.   top: 50%;
  21.   transform: translateY(-50%);
  22.   padding: 12px;
  23.   font-size: 2rem;
  24.   width: 25px;
  25.   height: 25px;
  26.   text-align: center;
  27.   color: #000;
  28.   border-radius: 50%;
  29.   border: 3px solid #000;
  30. }
This gives us the result as shown below:


Limitations

At this point, it’s important to note that pseudo-elements aren’t 100% accessible. To test this I made a quick test. I installed NVDA and used Chrome 50, Firefox 45, and Internet Explorer 11 to preview the demo page.

What I found is that when the Internet Explorer was used, the screen reader didn’t announce the generated content. These days the majority of screen readers recognize generated content of this kind, yet you should be aware of the possible limitations, and therefore decide which content is safe enough to generate using pseudo-elements.

CSS Counters in the Wild

Now that we know the basics of CSS counters, we’re ready to show a few examples that demonstrate their potential use cases.

Firstly, CSS counters are commonly used in online newspapers. Most of the time, you’ll find them in sidebars:
Wall Street Journal
Handelsblatt

CSS counters can also be used within sections which describe steps, or give directions. Here’s just such an example:

SpikeNode  
Examples of Bloated HTML

In the previous section, we saw two online newspapers that take advantage of CSS counters. Now, let’s see another two newspapers which use bloated markup (albeit with accessible content) instead of CSS counters:

Washington Post
Guardian  
Conclusion

In this quick tip, we learned how we can use CSS counters to style ordered list items. Let’s briefly summarize what we’ve covered:
  • CSS counters are a great solution for every project that requires dynamic ordering with custom styles. On the other hand, this isn’t a fully accessible solution, so be aware of its limitations and use it properly.
  • To set up the counters, we have to specify two properties (i.e. counter-reset,counter-increment) and one function (counter() or counters()).
  • Pseudo-elements are responsible for displaying the counters. Remember that’s happening via the conten property, which is only available to pseudo-elements.
Written by George Martsoukos

If you found this post interesting, follow and support us.
Suggest for you:

Friday, August 12, 2016

Selecting Parent Elements with CSS and jQuery_part 2 (end)

Possible Workarounds

As we’ve covered, there is no such thing as a parent selector, so selecting a parent isn’t possible. We might be tempted to sidestep the problem, by completely reconsidering the design so that selecting the parent is avoided. But if that isn’t possible then here are some potential approaches.

Using CSS :has()Selector 
The :has selector is officially referred to as the relational pseudo-class. It matches elements based on their descendants, which are defined between the parentheses.

In the following example, it applies a background-color to any div containing an image caption. This seemingly addresses case 1.
  1. .page-content div:has( .img-caption ) {
  2.     padding: 15px;
  3.     background-color: #ccc;
  4. }
Or, if we want to be more specific, we can rewrite it to match any div tag with the .img-caption as the direct descendant.
  1. .page-content div:has( > .img-caption ) {
  2.     padding: 15px;
  3.     background-color: #ccc;
  4. }
This selector is drafted for CSS Selector Level 4 though no browsers implement it yet. We will have to wait a little longer before this selector comes to light.

Using the jQuery Parent Selector
No single CSS solution can fix our issues here, so let’s see what JavaScript can do for us instead. In this example we are going to use jQuery for its robust APIs, convenience, and browser compatibility. At the time of writing, jQuery provides three methods to select parent elements.

parent(); this method selects the immediate parent of the targeted element. We can leverage this method to address all our use cases mentioned earlier in the tutorial.

Image structure in legacy content.
For example, we may use parent() to add a special class to the wrapping element of the images within the content.
  1. $( ".img-caption" )
  2.     .parent()
  3.         .addClass( "has-img-caption" );
The above code will select the immediate element wrapping the image, regardless of the element type, adding the has-img-caption class to give us more control over the element selection and styles, as follows.
Image structure in legacy content with an extra class.
parents() notice the plural form of this method. This method allows us to select the parent elements from the immediate, up to the root of the document, unless a selector is specified as the argument.
  1. $( ".img-caption" )
  2.     .parents()
  3.         .addClass( "has-img-caption" );
Given the above example, the parents() method selects all the way from the div tag which immediately wraps the image, the next div, and lastly the html, adding the has-img-caption class to all elements.

The has-img-caption class applied with the parents() method.
Such overkill is redundant. The only element that will likely need to have the class added, in this case, is the immediate div element. Hence we pass it in the method argument.
  1. $( ".img-caption" )
  2.     .parents( "div" )
  3.         .addClass( "has-img-caption" );
Here, the parents() method will travel through the ancestor tree of the image, selecting any div found and giving it the has-image-caption class.

If that’s still overbearing, you can narrow the selection down to a single element by specifying the index. In the following example, we apply the class only to the first div.
  1. var $parents = $( ".caption" ).parents( "div" );
  2.     $parents[0].addClass( "has-img-caption" ); // select the first div add add the class.
parentsUntil(); this method selects the parent elements up to but not including the element specified in the parentheses.
  1. $( ".caption" )
  2.     .parentsUntil( ".page-content" )
  3.         .addClass( "has-img-caption" );
Given the above code, it will apply the has-img-caption class to all the parent elements except the element with .page-content.


In some cases, where you have gazillion nested elements, using the parentsUntil() method is preferable. It is comparably faster than the parents() method as it avoids using the jQuery selector engine (Sizzle) to travel across the entire DOM tree up to the document root.

Wrapping Up

Are we likely to have a CSS Parent Selector at some point in the future?

Probably not. The kind of parent selector that we’ve discussed above has been proposed numerous times, but it has never passed the W3C draft stage for several reasons. Those reasons largely focus on browser performance, owing to the way browsers evaluate and render pages. The closest thing we’ll have in the future is the relational selector, :has().

However, since the :has() is not yet applicable, JavaScript and jQuery are currently the most reliable approach. Bear in mind that DOM Traversal is a costly operation which may badly affect your site’s rendering performance. Avoid using parents() or parentsUntil() with other heavy operations like animate()fadeIn() or fadeOut().

Better yet, examine the HTML structure whenever possible to see if selecting the parent element can be avoided completely!
Written by Thoriq Firdaus

If you found this post interesting, follow and support us.
Suggest for you:

CSS: Foundation classes on CSS

Coding Made Easy: HTML & CSS For Beginners

Bootstrap 4 Rapid web development framework HTML CSS JS


Thursday, August 11, 2016

Selecting Parent Elements with CSS and jQuery_part 1

There have been occasions where I’ve wished I was able to select a parent element with CSS–and I’m not alone on this matter. However, there isn’t such thing as a Parent Selector in CSS, so it simply isn’t possible for the time being.

In this tutorial we will walk through a few cases where having a CSS parent selector might come in handy, along with some possible workarounds. Let’s get started!

Wait, What’s a Parent Selector?

CSS selectors allow us to target elements, moving down and across the DOM tree, getting more specific as we do so. Here’s an example of the kind of selector you might find in Bootstrap–it travels down the DOM tree from the nav.navbar-dark element, to the ul, the li, then finally the a.nav-link.
  1. .navbar-dark .navbar-nav .nav-item .nav-link {     
  2. }
 A parent selector would allow us to travel back up the DOM, targeting the parent elements of certain things. For example, we would be able to target the parent of .nav-link elements by using:
  1. .nav-link::parent {
  2. }
Note: this example is pure pseudo code, it does not exist nor suggest the best possible syntax!

Case 1: Styling Legacy Content

Styling legacy content, with dated markup and structure, is a classic challenge when redesigning a website. Before HTML5, for example, an image might typically have been wrapped with a pdiv, or sometimes with a span along with a nested p used to wrap the image caption. There was no standard way to wrap an image and caption. Later, we adopted the figure and figcaption  elements, making our document structure more semantic.


We want the images from the legacy content to appear as above. But since there may be more div tags in our document, ones which don’t contain images at all, the following style declarations would be completely impractical.
  1. .page-content div {
  2.     padding: 15px;
  3.     background-color: #f3f3f3;
  4.     margin: 10px 0 20px;
  5. }
  6. .page-content div img {
  7.     marging: 0 0 10px;
  8. }
  9. .page-content div .img-caption {
  10.     color: #999;
  11.     font-size: 12px;
  12.     text-align: center;
  13.     Wisplay: block;
  14. }
It would apply the background color, padding and margins to all div elements in the content. We actually want to apply these styles exclusively to div elements which wrap an image and an image caption.

Case 2: Maintaining Video Ratio

Another example looks at maintaining embedded video (like from Youtube or Vimeo) ratio, as well as making the video fluid. These days, largely thanks to the investigative work by Dave Rupert and pals, it’s widely accepted that the best approach is to apply padding-top or padding-bottom to the parent element.
Code snippet from CSS-Tricks: Fluid width video
In a real world, however, we may would not know which element contains the video. We may find some embedded video wrapped within a div or a p without an identifiable class name, making it tricky to select the proper element on which to apply the styles.

Therefore, declaring the styles as follows is again impractical since it will impact all the divs within the .page-content including ones which don’t contain an embedded video.
  1. .page-content {
  2.     width: 560px;
  3.     margin-right: auto;
  4.     margin-left: auto;
  5.     margin-top: 30px;
  6. }
  7. .page-content div {
  8.     position: relative;
  9.     padding-bottom: 56.25%;
  10. }
  11. .page-content div iframe {
  12.     position: absolute;
  13.     top: 0;
  14.     width: 100%;
  15.     height: 100%;
  16. }
How wonderful it would be to directly select the video’s parent element!

Case 3: Responding to Form Input

In this example we have a form with several inputs. When we focus on one of the inputs, it is given a more prominent border color, highlighting the user’s position within the form.

Sometimes you also may come across the situation where not only the border color, but the element wrapping the input is highlighted, making the input even more prominent:
Input form focus.
The parent element might be a div or a p. So, how can we properly select the parent element based on certain states of its descendants?
Written by Thoriq Firdaus

If you found this post interesting, follow and support us.
Suggest for you:

CSS: Foundation classes on CSS

Coding Made Easy: HTML & CSS For Beginners

Bootstrap 4 Rapid web development framework HTML CSS JS

Monday, August 8, 2016

How to Build a News Website Layout with Flexbox_part 2 (end)

5. Give the First Article a Horizontal Layout

The first article is really big. To optimize the use of space, let’s switch its layout to be horizontal.
  1. .first-article {
  2.   flex-direction: row;
  3. .first-article .article-body {
  4.   flex: 1;
  5. .first-article .article-image {
  6.   height: 300px;
  7.   order: 2;
  8.   padding-top: 0;
  9.   width: 400px;
  10. }
The order property is very useful here, as it allows us to alter the order of HTML elements without affecting the HTML markup. The article-image actually comes before the article-body in the markup, but it will behave as if it comes after.


6. Make the Layout Responsive

This is all looking just as we want, though it’s a bit squished. Let’s fix that by going responsive.

One great feature of Flexbox is that you need only remove the display: flex rule on the container to disable Flexbox completely, while keeping all the other Flexbox properties (such as align-items or flex) valid.

As a result, you can trigger a “responsive” layout by enabling Flexbox only above a certain breakpoint.

We’re going to remove display: flex from both the .columns and .column selectors, instead wrapping them in a media query:
  1. @media screen and (min-width: 800px) {
  2.   .columns,
  3.   .column {
  4.     display: flex;
  5.   }
  6. }
That’s it! On smaller screens, all the articles will be on top of each other. Above 800px, they will be laid out in two columns.

7. Add Finishing Touches

To make the layout more appealing on larger screens, let’s add some CSS tweaks:
  1. @media screen and (min-width: 1000px) {
  2.   .first-article {
  3.     flex-direction: row;
  4.   } 
  5.   .first-article .article-body {
  6.     flex: 1;
  7.   } 
  8.   .first-article .article-image {
  9.     height: 300px;
  10.     order: 2;
  11.     padding-top: 0;
  12.     width: 400px;
  13.   } 
  14.   .main-column {
  15.     flex: 3;
  16.   } 
  17.   .nested-column {
  18.     flex: 2;
  19.   }
  20. }
The first article has its content laid out horizontally, with the text on the left and the image on the right. Also, the main column is now wider (75%) and the nested column too (66%). Here’s the final result!


Conclusion

I hope I’ve shown you that you needn’t understand every aspect of Flexbox to jump in and start using it! This responsive news layout is a really useful pattern; pull it apart, play with it, let us know how you get on!
Written by Jeremy Thomas

If you found this post interesting, follow and support us.
Suggest for you:

CSS: Foundation classes on CSS

Coding Made Easy: HTML & CSS For Beginners

Bootstrap 4 Rapid web development framework HTML CSS JS


Friday, August 5, 2016

How to Build a News Website Layout with Flexbox_part 1

What You'll Be Creating
It’s not necessary to understand every aspect of Flexbox before you can jump in and get started. In this tutorial, we’re going to introduce a few features of Flexbox whilst designing a “news layout” like the one you can find on The Guardian.

The reason we’re using Flexbox is that it provides very powerful features:
  • we can easily make responsive columns
  • we can make columns of equal height
  • we can push content to the bottom of a container
So let’s get started!

1. Start with Two Columns

Creating columns in CSS has always been a challenge. For a long time, the only options were to use floats or tables, but they both had their own issues.

Flexbox makes the process easier, giving us:
  • cleaner code: we only need a container with display: flex
  • no need to clear floats, preventing unexpected layout behavior
  • semantic markup
  • flexibility: we can resize, stretch, align the columns in a few lines of CSS
Let’s start by making two columns; one that’s 2/3 of the width of our container, and one that’s 1/3.
  1. <div class="columns">
  2.   <div class="column main-column">
  3.     2/3 column
  4.   </div>
  5.   <div class="column">
  6.     1/3 column
  7.   </div>
  8. </div>
There are two elements here:
the columns container
two column children, one with an additional class of main-column which we’ll use to make it wider
  1. .columns {
  2.   display: flex;
  3. }
  4.  column {
  5.   flex: 1;
  6. }
  7. .main-column {
  8.   flex: 2;
  9. }
As the main column has a flex value of 2, it will take up twice as much space as the other column.
By adding some additional visual styles, here’s what we get:


2. Make Each Column a Flexbox Container

Each of these two columns will contain several articles stacked vertically, so we’re going to turn the column elements into Flexbox containers too. We want:
  • the articles to be stacked vertically
  • the articles to stretch and fill the available space
  1. .column {
  2.   display: flex;
  3.   flex-direction: column; /* Makes the articles stacked vertically */
  4. } 
  5. .article {
  6.   flex: 1; /* Stretches the articles to fill up the remaining space */
  7. }
The flex-direction: column rule on the container, combined with the flex: 1 rule on the children ensures that the articles will fill up the whole vertical space, keeping our first two columns the same height.


3. Make Each Article a Flexbox Container

Now, to give us extra control, let’s turn each article into a Flexbox container too. Each of them will contain:
  • a title
  • a paragraph
  • an information bar with the author and the number of comments
  • an optional responsive image
We’re using Flexbox here in order to “push” the information bar to the bottom. As a reminder, this is the article layout we’re aiming for:


Here’s the code:
  1. <a class="article first-article">
  2.   <figure class="article-image">
  3.     <img src="">
  4.   </figure>
  5.   <div class="article-body">
  6.     <h2 class="article-title">
  7.       <!-- title -->
  8.     </h2>
  9.     <p class="article-content">
  10.       <!-- content -->
  11.     </p>
  12.     <footer class="article-info">
  13.       <!-- information -->
  14.     </footer>
  15.   </div>
  16. </a>

  1. .article {
  2.   display: flex;
  3.   flex-direction: column;
  4.   flex-basis: auto; /* sets initial element size based on its contents  */
  5. } 
  6. .article-body {
  7.   display: flex;
  8.   flex: 1;
  9.   flex-direction: column;
  10. } 
  11. .article-content {
  12.   flex: 1; /* This will make the content fill up the remaining space, and thus push the information bar at the bottom */
  13. }
The article’s elements are laid out vertically thanks to the flex-direction: column; rule.

We apply flex: 1 to the article-content element so that it fills up the empty space, and “pushes” the article-info to the bottom, no matter the height of the columns.


4. Add Some Nested Columns

In the left column, what we actually want is another set of columns. So we’re going to replace the second article with the same columns container we’ve already used.
  1. <div class="columns">
  2.   <div class="column nested-column">
  3.     <a class="article">
  4.       <!-- Article content -->
  5.     </a>
  6.   </div> 
  7.   <div class="column">
  8.     <a class="article">
  9.       <!-- Article content -->
  10.     </a>
  11.     <a class="article">
  12.       <!-- Article content -->
  13.     </a>
  14.     <a class="article">
  15.       <!-- Article content -->
  16.     </a>
  17.   </div>
  18. </div>
As we want the first nested column to be wider, we’re adding a nested-column class with the additional style:
  1. .nested-column {
  2.   flex: 2;
  3. }
This will make our new column twice as wide as the other.


Written by  Jeremy Thomas
If you found this post interesting, follow and support us.
Suggest for you:

CSS: Foundation classes on CSS

Coding Made Easy: HTML & CSS For Beginners

Bootstrap 4 Rapid web development framework HTML CSS JS


Wednesday, August 3, 2016

Editing Images in CSS: Filters

Consider a situation where you have to have high-contrast, blurred or brighter versions of particular images on your website. Prior to CSS filters, your only options were either to upload different versions of these images or manipulate the images with JavaScript.

Unless you want to manipulate the pixels in the original image, CSS filters provide an easy way out. Let's begin this tutorial with a brief discussion of all available filters.

Blur Filter

This filter will apply a Gaussian blur to your images. You will have to provide a length value which will determine how many pixels need to blend into each other. This implies that a larger value will provide a more blurry image. Keep in mind that you can't use percentage to determine the blur radius. If you don't specify a parameter, then the value 0 is used. The proper syntax for using this filter is:

  1. filter: blur( <length> )

The blur() filter does not accept negative values.


Brightness Filter

This filter will apply a linear multiplier to your images, making them brighter or dimmer compared to the original images. It accepts a number as well as a percentage value. At 0% you will get a completely black image. At 100% you get the original image without any changes. Higher values will result in brighter images. A sufficiently high value will turn the image mostly white. The proper syntax to use this filter is:

  1. filter : brightness( [ <number> | <percentage> ] )

This filter does not accept any negative values either.


Contrast Filter

This filter changes the contrast of your images. Just like the brightness filter, it accepts a number as well as percentage values. A 0% value will result in a completely gray image. Setting the value to 100% does not have any effect. Values higher than 100% will produce high-contrast images. You are not allowed to use negative values with the contrast() filter. The proper syntax to use this filter is:

  1. filter : contrast( [ <number> | <percentage> ] )

Drop-Shadow Filter

Almost every one of you might have used box-shadows at least once. The problem with box-shadows is that they are boxy. You can't use them to create shadows of irregular shapes. On the other hand, the drop-shadow filter creates shadows around the boundary of an image. It is basically a blurred version of the alpha mask of the input image. The proper syntax to use drop-shadow is:

  1. filter : drop-shadow( <length>{2,3} <color>? )

The first two length values are required, and they set the horizontal and vertical shadow offset. The third <blur-radius> value is optional. A bigger value will create a lighter shadow. The demo below shows this filter in action. If you hover over the penguin, the color of the shadow will change from orange to red.
Grayscale Filter

This filter will make your images grayscale. A 0% value will leave the image unchanged, while a 100% value will make the image completely grayscale. Any value between these two effects will be a linear multiplier on this effect. You can't use negative values with the grayscale() filter. The proper syntax to use this filter is:

  1. filter : grayscale( [ <number> | <percentage> ] )



This filter will apply a hue rotation on your images. The parameter (passed as an angle) will determine the number of degrees around the color circle the images will be adjusted. With a 0deg value the final image will be unchanged. If you specify a value beyond 360deg, the filter just wraps around. The proper syntax to use this filter is:
  1. filter : hue-rotate( <angle> )


This filter will invert your images. The amount of inversion depends on the value of the parameter that you passed. A 0% inversion will have no effect on the image. On the other hand, a value of 100% will completely invert the image. A 50% value will produce a completely gray image. Any value between the extremes will be a linear multiplier of the effect. This filter does not accept negative values. The proper syntax to use the invert() filter is:
  1. filter : invert( [ <number> | <percentage> ] )


The opacity filter applies transparency to input image. A value of 0% implies you want 0% opacity, which results in complete transparency. Similarly, a 100% value results in a completely opaque image. 

The filter is similar to the opacity property in CSS. The only difference is that in this case some browsers may provide hardware acceleration for improved performance. The proper syntax to use this filter is:
  1. filter: opacity( [ <number> | <percentage> ] );


This filter determines the saturation of your images. The saturation itself depends on the value of the parameter. You can't use negative values with this filter. At 0%, the minimum possible value, the image will be completely unsaturated. With a saturation value of 100%, the image remains unchanged. To get super-saturated images, you will have to use values over 100%. The proper syntax to use this filter is:
  1. filter : saturate( [ <number> | <percentage> ] )


This filter will transform your original images to sepia. At 100% value you will get a complete sepia, and a 0% value will not have any effect on the image. All other values that lie in between will be linear multipliers of this filter. You are not allowed to use negative values with this filter. The proper syntax to use the sepia() filter is:
  1. filter : sepia( [ <number> | <percentage> ] )


There might be situations when you want to use your own filters on images. The url filter will take the location of an XML file that specifies an SVG filter. It also accepts an anchor to a specific filter element. Here is an example which results in posterization of our image:
  1. // The filter
  2.  
  3. <svg>
  4.   <filter id="posterize">
  5.     <feComponentTransfer>
  6.       <feFuncR type="discrete" tableValues="0 0.33 0.66 0.99" />
  7.       <feFuncG type="discrete" tableValues="0 0.33 0.66 0.99" />
  8.       <feFuncB type="discrete" tableValues="0 0.33 0.66 0.99" />
  9.     </feComponentTransfer>
  10.   </filter>
  11. </svg>
  12.  
  13. // Required CSS to apply this filter
  14.  
  15. filter: url(#posterize);
The final result after applying the filter would look similar to the following image:



If you are not satisfied with the output of an individual filter, you can apply a combination of them on a single image. The order in which you apply the filters can produce marginally different results. Multiple filters can be applied in the following manner:
  1. filter : sepia(0.8) contrast(2);
  2. filter : saturate(0.5) hue-rotate(90deg) brightness(1.8);

When you use multiple filters together, the first filter function in the list is applied on the original image. Subsequent filters are applied to the output of the previous filters. This demo shows two other filter combinations in action.

In some special circumstances, the order of filters can produce completely different results. For instance, using sepia() after grayscale() will produce a sepia output, and using grayscale() after sepia() will result in a grayscale output.

Animating the Filters

The filter property can be animated. With the right combination of image and filters, you can exploit this feature to create some stunning effects. Consider the code snippet below:
  1. @keyframes day-night {
  2.   0% {
  3.     filter: hue-rotate(0deg) brightness(120%);
  4.   }
  5.   10% {
  6.     filter: hue-rotate(0deg) brightness(120%);
  7.   }
  8.   20% {
  9.     filter: hue-rotate(0deg) brightness(150%);
  10.   }
  11.   90% {
  12.     filter: hue-rotate(180deg) brightness(10%);
  13.   }
  14.   100% {
  15.     filter: hue-rotate(180deg) brightness(5%);
  16.   }
  17. }
I am using the hue-rotate() and brightness() filter together to create the illusion of day and night. The original image itself has an orange hue. For up to 20% of the animation, I increase the brightness gradually and keep the hue-rotation at zero. This creates the effect of a sunny day. By the time the animation ends, I rotate the hue by 180 degrees. This results in a blue hue. Combining this with very low brightness creates the effect of night. 

Final Thoughts

Besides the 11 filters we discussed above, there is also a custom() filter. It allows you to create completely different kinds of effects using shaders. There are a few issues with custom() filters which have halted their development. Adobe is working actively to come up with solutions to problems that crop up when using custom() filters. Hopefully, they will soon be available for developers to use in their projects.
Written by Monty Shokeen

If you found this post interesting, follow and support us.
Suggest for you: