About the Author:

Maintainable and Optimized CSS with CSS Modules

July 13th, 2017

There have been many techniques proposed to help developers develop maintainable and scalable CSS, some of which oppose each other rather directly. BEM was designed to avoid class name clashes, too much specificity, and is organized around components. When developing apps with JavaScript frameworks such as Vue or React, which are component-based, BEM seems like a great match.

BEM has some drawbacks though. If you have a fairly standardized set of colors, spacing sizes, and such, you’re going to have a whole lot of property repetition, resulting in a very large stylesheet. In that article linked to in the previous sentence, the author recommends having only one instance of a property/value pair and using a list of selectors to apply it to the proper elements. There are also suggestions out there proposing only the use of helper classes and only using those classes in your HTML. Then, of course, you’re left with tons of repetition in the HTML rather than in the CSS.

What if we could work with a component-centric CSS structure but keep the CSS and HTML clear of a lot of the repetition? This is where CSS Modules come in.

CSS Modules

CSS Modules is a specification developed primarily to aid in creating local-scope CSS classes and seems to be largely inspired by the BEM methodology but adds the scoping so that you need come up with absurdly long class names. A build tool is used to convert your CSS classes (the ones you don’t mark as global anyway) to be unique, generally via a hashing method.

So how do you use the correct classes if they’re going to change once the application is built? Well, CSS Modules are meant to be imported into a JavaScript file, which will give you access to a mapping between your original class names and the compiled ones.

For instance, you could have a CSS file like this:

/* color-scheme.css */
.standardColors {
background: white;
color: black;
}

.invertedColors {
background: black;
color: white;
}

You can then import that CSS into a JavaScript module, and the import will be an object with the class mapping, which you can use in your HTML output:

import styles from './color-scheme.css'

export default 
<div class="${styles.standardColors}">This is standard</div>
<div class="${styles.invertedColors}">This is inverted</div>

The styles object has properties with names matching the classes in the CSS file and their values refer to the hashed versions of those classes. So this allows us to create a CSS file for each component and make our CSS similar to BEM without the need for the naming convention, but it doesn’t solve the problem of repetition. So let’s look at the next feature of CSS Modules: Composition.

For this we’ll need some more CSS files:

/* base-styles.css */
.cozyMargin {
margin: 5px;
}
.comfyMargin {
margin: 25px;
}
.cozyPadding {
padding: 5px;
}
.comfyPadding {
padding: 25px;
}
/* comfy-box.css */
.box {
composes: comfyMargin comfyPadding from './base-styles.css'
}
//js
import styles from './comfy-box.css'

export default 
<div class="${styles.box}">This box is comfy</div>

The key here is in comfy-box.css where you see the composes “property”. This essentially allows .box to be composed of the same styles as the classes we added (comfyMargin and comfyPadding from the base-styles.css file in this case). How exactly is this accomplished though? To see that we need to looks at value of styles.box in the JavaScript: "box comfyMargin comfyPadding". These classes are actually getting hashed, so that’s not really what styles.box would be, but if they weren’t hashed, that’s what it would be. Once the CSS is all done processing (by a CSS Modules tool) and being combined, the full CSS file will look like this:

/* combined.css */

/*
Note: Simply adding '-h45h' like I did below is not actually what would happen. It's just that way for simplicity in this example.
*/

.cozyMargin-h45h {
margin: 5px;
}
.comfyMargin-h45h {
margin: 25px;
}
.cozyPadding-h45h {
padding: 5px;
}
.comfyPadding-h45h {
padding: 25px;
}
.box-h45h { }

And the HTML output would look like this:

<div class="box-h45h comfyMargin-h45h comfyPadding-h45h">This box is comfy</div>

If you then run the CSS through a minifier, the box-h45h rule will be completely stripped out. The class will still show up on the HTML element, so you can still see what component the div is and know where to go if you need to make changes to the component or its CSS. This was just a quick and dirty intro to CSS Modules, with plenty of concepts and features left out, so if you’d like to really learn about CSS Modules, I suggest reading Glen Maddern’s introduction and the CSS Modules spec documentation for more information, including how to actually add the build step into your project.

The Proposal

You can see from the examples above that if every component was composed of those helper classes, rather than writing their own margin and padding rules, there would be no repetition of those rules. This is what the proposal is all about, except on a larger scale that covers more than just margin and padding helpers:

  1. Write 1 or more stylesheets containing lots of helper/utility classes with as few property declarations as possible to keep each rule set as succinct and reusable as possible.
  2. Each component has a stylesheet comprised of rule sets that almost exclusively use compose rather than writing their own property declarations. There will likely be exceptions where some of the styles for a component may be better off not being composed of helper classes.
  3. “Super helpers” can be written to compose several low-level helper classes into oft-used combinations of helpers.

This methodology has several benefits:

  1. The helper classes can help enforce rules regarding the use of certain units, colors, spacing, fonts, etc.
  2. On the same note, having all related helper classes near one another can help make it obvious when there are too many different values for a certain property and some consolidation should take place.
  3. As mentioned earlier, the total size of the CSS file(s) being served to the user is much smaller because it removes duplication.
  4. You write your JavaScript and component CSS in a component-based way, which is simplest for development when using component-based frameworks, but the output is more optimized for delivery.

And that’s it. CSS Modules enable you to organize and structure your CSS in many different ways while still keeping everything component-based and not needing to worry about global name clashing. Of course, there are other legitimate ways, so if you think you have a better way, feel free to let us know. I’m sure we can all learn from one another.

About the Author:

What Exactly is Mobile-first Web Design?

March 14th, 2017

Are you reading this on a mobile device? If so, you aren’t alone. With close to 87% of internet users owning smartphones, it stands to reason that more and more people are doing their internet browsing and research through mobile means.

Mobile-first web design is the practice of designing and developing websites to be viewed on mobile devices first, before working on a desktop view. By optimizing your website for mobile viewing, you can ensure that if anyone happens upon your website while using their smartphone, they won’t be turned away by unreadable text or unclickable links.

The History of Mobile Devices

The term smartphone has been around since 1995, but the first smartphone to feature modern touchscreen technology was the iPhone, which came out in 2007. With this, websites were launched into the mobile world, forever changing web design and development best practices.

Since then, technology has continued to give us more devices that are capable of accessing the internet, including, but not limited to; Smart TVs, gaming consoles, and smartwatches. With so many platforms that people can view websites on, it’s more important than ever to design for more than just the standard desktop view.

Internet Browsing Statistics

Statistics courtesy of “Mobile Marketing Statistics Compilation”, Smart Insights

So, why practice mobile-first web design? Why not tablet-first, or smartwatch-first design? The term mobile, while typically used to refer to phones, is not exclusive to smartphones. The principle behind mobile-first web design is that you design for the smallest possible screen first, and scale your way up to larger sizes. The smallest possible screen size may change over time, but the mobile-first method applies regardless of what screen resolution or device you start out with.

In this article, we’ll cover what different website elements feel like in a mobile environment, how to implement them using both responsive and adaptive design, and what to remain aware of when working with mobile devices and small screens.

Website Elements and Mobile Devices

Most of us are familiar with the various elements that are found on a webpage – logos, navigation, sliders, headers, copy, footers, etc. But in order to learn how these should work on mobile devices, you’ll need to take a closer look at the base elements of a website – text, buttons, and images.

Text

One of the most common elements of any website is text. Text is located all over traditional webpages, from headers and copy, to links and descriptions. The most common problem encountered on a mobile device is that text is too small to read, forcing users to zoom in on your website in order to view it. However, text that is too large can also cause problems – if only a small amount of text can fit on the screen at a time, this is just as poor an experience for mobile users.

Paying close attention to the font sizes used on your website at different screen resolutions can go a long way towards ensuring mobile compatibility. There are four different ways to set the size of your text – pixels, points, ems, and percents.

font-size: 16px;
font-size: 12pt;
font-size: 1em;
font-size: 100%;

Pixels and points are fixed units that tend to appear on the web and in print documents, respectively. Ems and percents are relative units that change based on browser settings and screen resolution.

So, which one is better to use for mobile-first web design? Best practices indicate using percents for the best all-around experience, but any of these sizing methods can work with the help of media queries. The best way to find out what works for you and your website is to simply test it out!

Mobile-Friendly Font Sizes

Note: Having the right text for a mobile experience is about more than just selecting the proper font size. Font family, weight, color, text decoration and transformations, line heights, and letter spacing can also play a large part in readability on both mobile and desktop devices.

Buttons

If you have visited any website recently, you’re sure to have seen a call-to-action button encouraging you to explore other parts of the website, or a submit button for a form. They’re an essential part of any site, and yet one of the more problematic elements for anyone new to mobile-first design.

Buttons, similar to text, can have readability issues that are related to font size. But they also can have issues with providing too small of a clickable area for mobile users, and being too close to other clickable elements on a website.

The most important part of making buttons mobile-friendly is ensuring that users are able to comfortably tap on the button while scrolling on their mobile device, which means allowing a space for the user’s entire finger or thumb to touch the button. You can give users this space on the button height, the button width, or the margin surrounding the button.

The average width of an adult index finger is 2cm, which is approximately 57 pixels, while the average width of an adult thumb is 1 inch, which is approximately 72 pixels. This means that at it’s smallest size, a button should always have a height of 72px and a width of 144px, in addition to a margin of error that gives at least 10 pixels of additional space on either side.

Mobile-Friendly Buttons

.tiny {
  width: 144px;
  height: 72px;
  margin: 10px 0px 10px 0px;

.small {
  width: 288px;
  height: 72px;
  padding: 10px 10px 10px 10px;
}

.large {
  width: 288px;
  height: 144px;
  margin: 10px 10px 10px 10px;
}

.long {
  width: 90%;
  height: 72px;
  padding: 10px 0px 10px 0px;
}

Images

While websites are not usually constructed entirely from images as they were back when the internet was still young, they are still one of the most prevalent elements of webpages, showing up in large sliders and carousels, attached to product and page descriptions, and scattered across pages as icons or visual cues.

Unlike text and buttons, images can be scaled to fit anywhere with the same aspect ratio. This is the proportion of an image’s width compared to its height, with the most common ones being 16:9, 4:3, and 3:2. As your image scales in size, the aspect ratio should remain the same, giving your image relatively the same appearance across all screen sizes.

Because images are used in so many different places on websites, the way they should be displayed on mobile devices depends heavily on their intended usage, and what other elements of a website they have been paired with, if any. The most popular use of images these days is in sliders.

Image Sliders

Many websites feature a large image slider, or carousel, on their homepage. They provide an immediate visual representation of products or services, and tend to grab a user’s attention as soon as they land on a page.

Sliders in particular tend to challenge design best practices as we know them. Here are a couple considerations when implementing sliders for a mobile device:

  1. If the aspect ratio of the image is large, and you intend the user to be able to scroll on the website, then the entire slide cannot link somewhere. A button should be used instead so people do not go to a different page on accident. However, if the aspect ratio of the image is small, then a button does not necessarily need to be used.
  2. The text located on your slider must be able to scale proportionately to the image, while still keeping with current mobile text standards. If you cannot appropriately scale the text, you may need to cut down on the amount of text or eliminate it altogether.
  3. When on mobile, the text you have on your slider must not cover the entire image in a such a way that the purpose of the image becomes lost. If the message conveyed via text is more important than the image itself, you may need to remove the image or replace it with a more generic image.

Mobile-Friendly Image Sliders

Sliders are also one of the places on websites where we can clearly see the impact of mobile-first design. Before mobile-first design was popular, most sliders were a single, linked image with an area reserved for text. Now, because of mobile-first design, they usually feature only a small amount of text, and a button to prompt users to scroll down or reach a new area of the website.

Sliders Before Mobile-First Design

Slider Image

Sliders After Mobile-First Design

Slider Image

Note: You might be tempted to use a small image when using mobile-first design, but don’t forget to save a high resolution copy of your image for desktop use. Large images typically scale down just fine, but scaling up a small image can cause a loss of quality that makes your website look unprofessional.

Implementing Designs on Mobile Devices

Most web developers don’t get the chance to preview their work on a mobile device right away – many use a small browser window to view, test, and debug code at small screen sizes. When you go to make any mobile-friendly website, make sure to include the following meta tag in the head of your HTML:

<meta name="viewport" scale="width=device-width,initial-scale=1">

By including this meta tag, you are telling any device that loads your website to base the width your website is shown at on the physical width of the device’s screen, and that the initial view of your website should not be scaled either up or down from the intended view.

In addition to the meta tag, you will also need to add this code snippet to your CSS to ensure compatibility on any devices running Windows 8 and using IE10:

@-ms-viewport {width: device-width;}

Neither the meta tag nor the CSS rule will assist you in actually writing your code for mobile devices, however – they will only make sure that code works as expected when implemented. In order to write your code, you’ll need the help of media queries – and in order to know what media queries to write, you may need the assistance of one of the following popular web design approaches.

Responsive Design

Responsive design is a web design and development process that responds to the size of the viewport. As the size of the viewport changes, elements on the webpage will increase or decrease in size or fall into place accordingly.

This approach is often used in conjunction with fluid layouts, as both feature a seamless transition between various viewport sizes. The main difference that sets responsive design apart from a true fluid layout, however, is that the elements can change at different times, and in different ways than a fluid layout would allow.

Responsive design is popular with many web developers and is considered the current best practice for web design due to the freedom it allows with designs. You set your own breakpoints according to the width of a viewport, and you decide where to set your breakpoints based on how the layout looks as you change the size of your viewport.

Having trouble writing your media queries? Check out CSS Media Queries to view the full complement of available media queries for your website. Don’t be afraid to try out new combinations, either – there’s no wrong way to set breakpoints with responsive design.

Adaptive Design

Adaptive design is a web design and development process that adapts to the size of the viewport. As the size of the viewport changes, the entire layout of the page or certain areas of the page will change once a certain breakpoint has been reached.

Adaptive design isn’t quite as clear-cut as responsive design, because the definition of what adaptive design really is has grown over time. So when a website is using adaptive design, that means they could be doing one or more of these things:

  • Using a completely separate mobile and desktop website or design, where the mobile version typically allows users to access the desktop version if they would like to
  • Showing one of any number of pre-defined layouts based on the original viewport size at the time of page load, and keeping that layout even if the viewport size is changed
  • Adding or removing a certain element or set of elements based on device type or viewport size, which may or may not change when the viewport size is changed
  • Completely changing the layout or design of either the website or any elements based on device type or viewport size, which may or may not change when the viewport size is changed

That being said, adaptive design provides users with a set of breakpoints based on popular devices and common screen resolutions:

@media only screen and (min-device-width:320px) and (max-device-width:640px) {
  /* All Smartphones */
}

@media only screen and (min-width:321px) {
  /* All Smartphones - Landscape Only */
}

@media only screen and (max-width:320px) {
 /* All Smartphones - Portrait Only */
}

@media only screen and (min-device-width:768px) and (max-device-width:1024px) {
  /* All Tablets */
}

@media only screen and (min-device-width:768px) and (max-device-width:1024px) and (orientation:landscape) {
  /* All Tablets - Landscape Only */
}

@media only screen and (min-device-width:768px) and (max-device-width:1024px) and (orientation:portrait) {
  /* All Tablets - Portrait Only */
}

@media only screen and (min-width:1224px) {
  /* All Desktops & Laptops */
}

@media only screen and (min-width:1824px) {
  /* Large Screens */
}

While this is just a basic set of breakpoints, websites that use adaptive design have many more than just these. Often they will include height as a parameter, or they’ll use -webkit-device-pixel-ratio to target specific devices. Don’t forget to look up more breakpoints, as well – the min and max widths used change all the time depending on which devices are currently popular and what current website standards place screen resolutions at.

NOTE: While responsive design is considered the current best practice for mobile-first web design, adaptive design is often easier to start with the first time you make a mobile-friendly website. Use whichever one you feel would be best for you, and don’t be afraid to mix these design types together if needed!

Additional Considerations

Designing for mobile devices isn’t always about meeting current website standards – when using their phones or tablets, people have a certain expectation for the way elements are displayed, and it’s okay to design your website a little more like a mobile app for the best user experience.

Here are several things that you should keep in mind about the mobile website experience that differ from a traditional desktop experience:

  • Hover effects don’t always work as expected. While the support for hover effects in mobile devices has increased in the past several years, there’s still no one-size-fits-all solution. Make sure hover effects aren’t the only way the individuality of your website is expressed, and don’t lock any content behind a hover effect.
  • Images and other resources don’t always load quickly. On a desktop computer, the amount of files you can add may seem unlimited, but mobile devices can quickly become overwhelmed by the number of files and their file size. Consider loading alternative, smaller versions of files for mobile devices to keep your loading time to a minimum.
  • People can’t always reach the top half of their mobile device. Most people are willing to move their mouse anywhere on the screen for a bright and friendly call-to-action on desktop computers, but with the mostly one-handed operation of mobile devices people usually only select items towards the bottom of the screen. If you have a single, revenue-driving call-to-action button, you might want to always keep it visible towards the bottom of the screen.
  • Mobile compatibility impacts Google search results. If your website is not mobile-friendly, Google will not serve it to mobile searchers. In addition to following the guidelines for website elements in this article, make sure your robots.txt file isn’t blocking any CSS, JS, or images that tell Google your page has been built for a mobile display.

Not sure if your website is mobile-friendly? Run it through Google’s Mobile-Friendly Test to find out!

Now It’s Your Turn!

With overall mobile usage now surpassing desktop computer usage, it’s more important than ever to switch to a mobile-first thought process for designing and developing websites. By keeping in mind how various elements look on mobile devices, and the principles of responsive and adaptive design, you should be able to design your website for any device or screen size. And don’t forget to test out your work on a real mobile device – even the best emulators can’t compare to the real thing.

About the Author:

RGB to Hex: Understanding the Major Web Color Codes

February 24th, 2017

Since the earliest days of web development, there have been ways to specify colors in backgrounds, borders, fonts, and other elements. Some people use supported color keywords, while other people use a more specific color system such as HSL (hue, saturation, lightness). However, today we will be talking about the two most popular color naming conventions, RGB color codes and hexadecimal (hex) color codes.

RGB Color Codes

RGB color codes, sometimes referred to as RGBA color codes when they include an additional value for an alpha channel, are one of the most popular ways to define colors in webpages. They are written in the following way:

color: rgb(0, 0, 0);       /* black */
color: rgb(255, 255, 255); /* white */

RGB gets its name from the primary colors; red, green, and blue. In traditional color theory, all other colors can be derived from combinations of these three, and it was thought that these three colors could not be formed by a mix of any other colors.

RGB Primary Color Wheel

Hex Color Codes

Hex color codes actually use the same principle as RGB color codes, as they both define colors using the RGB color mode. They are written in a slightly different way:

color: #000000; /* black */
color: #FFFFFF; /* white */

While the choice between which of these color naming conventions to use comes down to a matter of personal preference, there are several advantages to using hex color codes:

  • They are more compact, and therefore are better for minimized code. Hex color codes can also become even more compact by using only three digits for some colors, rather than the full six digits.
  • They improve the load time of a web page slightly. Computers handle binary digits, and one hexadecimal digit can easily be converted into four binary digits, while decimal digits take longer to convert.
  • They are easier to copy over from various programs that contain the color palette to be used, as they are written as one value rather than three separate values, and they are more likely to be used in color schemes being referenced since they have become the standard for use in HTML and CSS code.

While none of these are likely to make a significant impact on the development process, you may find yourself wanting to switch to hex color codes at some point – so, how does one switch from an RGB color code to a hexadecimal color code?

Converting RGB to Hex Color Codes

RGB color code values are based on the number system we are most familiar with, the decimal number system. The decimal number system is a Base-10 system, meaning there are 10 unique characters used to define the numbers. The 10 characters used are the numbers 0 – 9.

Hex color code values, in comparison, are based on the hexadecimal number system. The hexadecimal number system is a Base-16 system, meaning there are 16 unique characters used to define the numbers. The 16 characters used are the numbers 0 – 9, and the letters A – F.

Note: This also explains why the highest value possible in the RGB system is 255. By using a hexadecimal, or 16-bit number system, the maximum number of colors that can be displayed at any one time is 16 x 16, or 256 colors. These 256 colors are represented as the values 0 – 255.

Counting is done the same way in both systems. The first number is 0, and you count all the way up to the last digit. For the decimal number system, this digit is 9. For the hexadecimal number system, this digit is F. Sometimes, a leading 0 is written in front of these values. Once you reach the last digit, you start the count over, this time with your leading digit as the next one in the system (which is 1, for both the decimal and hexadecimal number systems). Below is a chart that helps to show the difference in the two number systems:

Decimal0123456789101112131415
Hexadecimal0123456789ABCDEF

In order to convert an RGB color code to a hex color code, you will need to convert each of the values individually. Let’s look at the color crimson as an example. The RGB color code for crimson is rgb(220, 20, 60).

Crimson: rgb(220, 20, 60)

First Value

  1. Take the first number, 220, and divide by 16. 220 / 16 = 13.75, which means that the first digit of the 6-digit hex color code is 13, or D.
  2. Take the remainder of the first digit, 0.75, and multiply by 16. 0.75 (16) = 12, which means that the second digit of the 6-digit hex color code is 12, or C.

So far, we have #DC____.

Second Value

  1. Take the second number, 20, and divide by 16. 20 / 16 = 1.25, which means that the third digit of the 6-digit hex color code is 1.
  2. Take the remainder of the first digit, 0.25, and multiply by 16. 0.25 (16) = 4, which means that the fourth digit of the 6-digit hex color code is 4.

Adding to what we had already, we now have #DC14__.

Third Value

  1. Take the third number, 60, and divide by 16. 60 / 16 = 3.75, which means that the fifth digit of the 6-digit hex color code is 3.
  2. Take the remainder of the first digit, 0.75, and multiply by 16. 0.75 (16) = 12, which means that the sixth digit of the 6-digit hex color code is 12, or C.

Finally, we have our total value of #DC143C.

Crimson: #DC143C

Converting Hex to RGB Color Codes

Despite the benefits of using hex color codes, there are times you might want to use an RGB color code instead. Some of the reasons you may choose to use an RGB color code, aside from personal preference, are:

  • You may need to add an alpha channel to the color itself, rather than using a separate CSS property for opacity.
  • You may expect people to print your web page, and printers understand RGB values better than they understand hexadecimal values.
  • You may need to manipulate colors with JavaScript, which becomes easier to do if you are using RGB color values.

Converting a hex color code to an RGB color code is actually a little more simple, as there is less math involved. This time, let’s look at the color orchid as an example. The hex color code for orchid is #DA70D6.

Orchid: #DA70D6

First Value

  1. Take the first digit, D, and convert it into decimal. The result is 13.
  2. Multiply 13 by 16. 13 (16) = 208. This is the partial value.
  3. Take the second digit, A, and convert it into decimal. The result is 10.
  4. Add the partial value to the second digit. 208 + 10 = 218.

This means that 218 is the red value.

Second Value

  1. Take the third digit, 7, and convert it into decimal. The result is 7.
  2. Multiply 7 by 16. 7 (16) = 112. This is the partial value.
  3. Take the fourth digit, 0, and convert it into decimal. The result is 0.
  4. Add the partial value to the second digit. 112 + 0 = 112.

This means that 112 is the green value.

Third Value

  1. Take the fifth digit, D, and convert it into decimal. The result is 13.
  2. Multiply 13 by 16. 13 (16) = 208. This is the partial value.
  3. Take the sixth digit, 6, and convert it into decimal. The result is 6.
  4. Add the partial value to the second digit. 208 + 6 = 214.

This means that 214 is the blue value, giving us our final result of rgb(218, 112, 214).

Orchid: rgb(218, 112, 214)

The Color Palette and You

No matter which method you prefer, both RGB and hex color codes are based upon the blending and intensity of three colors to create many different colors. However, colors on the web blend together differently than you might expect if you were to mix different color paint together.

Green + Blue = Cyan
Red + Blue = Magenta
Red + Green = Yellow

You might recognize these colors from another way of defining color in design, known as CMYK, which is used for printing. Some people prefer to think of the color palette not as the combination of RGB values to create CMYK values, but the combination of the CMYK values to create RGB values.

Magenta + Yellow = Red
Cyan + Yellow = Green
Cyan + Magenta = Blue
Cyan + Magenta + Yellow = Key (Black)

Knowing this, it becomes easier to understand what the individual RGB values control and how exactly to manipulate them to get the colors you are looking for.

Understanding the Sliding Scale

The sliding scale of color is what most representations of color palettes use in place of a color wheel. It goes through all the colors of the rainbow, starting at red, and continuing on through orange, yellow, green, blue, purple, and pink until it returns to red.

Color Sliding Scale

The red RGB value is responsible for warm color tones, such as red, pink, and orange. The higher this value is, the warmer the color will be. Red is the first color encountered on the sliding scale, with a value of rgb(255, 0, 0) or #FF0000.

As you work your way along the scale, more of the green RGB value is added to create orange, then yellow. Yellow, with a value of rgb(255, 255, 0) or #FFFF00, is the color that red and green have in common. From that point, the red value is decreased to give us different shades of green.

Eventually you will reach green on the sliding scale, with a value of rgb(0, 255, 0) or #00FF00. From there, the blue RGB value is added to eventually create cyan. Cyan, with a value of rgb(0, 255, 255) or #00FFFF, is the color that green and blue have in common. Similar to before, the green value is then decreased to create different shades of blue.

Towards the end of the sliding scale, you can start adding the red RGB value back in to create colors such as purple and pink. Once you reach Magenta, with a value of rgb(255, 00, 255) or #FF00FF, the blue value is then decreased to eventually reach the original red color you started with.

Variations in Individual Colors

Obviously, not all colors fit perfectly onto the sliding scale. By using the sliding scale, you will always be given very vibrant versions of colors – but sometimes, you need a lighter or darker shade of one of those colors to get the kind of color tone you’re looking for.

Web Safe Color Palette

Generally speaking, the higher the numbers, the lighter the color, and the lower the numbers, the darker the color. If you want to stick to the same shade of a color you have, this makes adjusting the brightness simple:

  1. Identify which color you are using out of the main choices on the sliding scale – red, green, blue, or a combination of two of them.
  2. If you would like to make the color lighter, adjust the values that are not being used – so for example, adjust green and blue if your color is red, or adjust only red if your color is cyan. The values will need to be higher numbers in order to lighten the color.
  3. If you would like the make the color darker, adjust only the values that are being used – so for example, adjust only red if your color is red, or adjust green and blue if your color is cyan. The values will need to be lower numbers in order to darken the color.

Note: If you are changing two values, the values will need to be adjusted evenly in order to make sure you keep the same color tone. That means if you increase or decrease one of the values by 100, you will need to also increase or decrease the other value by 100, regardless of if these numbers had the same starting value.

That’s a Wrap!

In conclusion, both RGB and hexadecimal values can be used to display colors on a web page. There is no right or wrong way to write color values, but each one has their advantages and disadvantages depending on the task you are trying to accomplish. Also, regardless of what color naming convention you use, you can easily manipulate your color tone by adjusting the values you’re using.

There isn’t a single technique that can give you a code for each and every color. Sometimes you need a more brilliant tone, or a cloudier one, that can’t be obtained by simply changing one or two values. Don’t be afraid to adjust all three values – the results might turn out better than what you were originally aiming for.

Now, go out and explore the color in your world!

About the Author:

The Basics of Using CSS Grid

February 1st, 2017

CSS Grid is a new, simple way of laying out the content of your website or app. Some of the shining features of the system are that grids can adapt to make use of available space. They are also very fast and can allow content to overlap. The whole premise of Grid was built around solving the hacky layout problems developers have been dealing with in CSS.

To be fair, this problem has been partially addressed with frameworks like Bootstrap or Foundation. But you still need to add libraries, learn intricacies, and are constricted to the principles of those frameworks. CSS grid has many advantages over these frameworks/libraries. CSS Grid is simple, easy to pick up, and built right into the browser.

CSS Grid will be pushed to production and supported by default in Firefox and Chrome in March 2017. If you’re about to stop reading as you’ve been burned before on buggy first releases, it’s important to note Grid has been in development for around 5 years & has had major changes. These have happened behind browser flags so there was no impact to users.

Trying CSS Grid Now

Until March 2017, you can still try out Grid behind an experimental flag. In Chrome, navigate to chrome://flags and enable “Experimental web platform features”. You’ll need to re-launch Chrome and then you’ll be ready to go. This is also available in Opera (opera://flags) and Firefox (about:config and enable layout.css.grid.enabled flag). It’s also been available in IE since version 10, but IE10, IE11, & Edge use old syntax, so it’s best to try it in Chrome, Firefox, or Opera.

Basic Terminology

Let’s cover some basic terminology before jumping into code samples. If you’re familiar with Excel, the Grid terminology is fairly easy to understand.

Grid: Any element with the display property set to grid.

Line: Horizontal and vertical lines that define boundaries.

Cells: Space between 4 grid lines.

Tracks: The space between two parallel lines.

Gutter: Space between cells.

Area: The area between 4 grid lines. This can have any number of cells.

C:\Users\Taylor\AppData\Local\Microsoft\Windows\INetCache\Content.Word\526pxgrid.png

Starting out, you’ll just need to create a parent element with a few child elements.


Box 1
Box 2
Box 3
Box 4
Box 5
Box 6

In the CSS, you’ll need to add display:grid to the parent element which identifies sets that element as a grid. You’ll need to set grid-template-columns and grid-template-rows, as these are needed to define your columns and rows. In this example, there would be two columns that each take up 25% and 50% of the grid & 3 rows with the first row having a height of 10px, the second row with a height of 50px, and the third row having a height of 100px.

.my-grid {

display: grid;

grid-template-columns: 25% 50%;

grid-template-rows: 50px 50px 100px;

grid-gap: 10px;

}

.square {

padding: 1em;

color: white;

text-align: center;

}

.yellow {

background-color: #f1c40f;

}

.blue {

background-color: #2a80b9;

}

.red {

background-color: red;

}

Now, add grid-column: 1 / span 2 to the blue class. This means it will span from the first gridline to the second. This concept can also be applied to rows and can create very detailed layouts. Notice how box 6 gets pushed to the next line.

.blue {

background-color: #2a80b9;

grid-column: 1 / span 2;

}

Although these examples are just the tip of the iceberg of CSS Grid, there are so many more features and things you can do with this. You’re probably going to have to learn CSS Grid at some point in the future, but if it’s too early to use as your entire layout, you can still use Grid in different UI components. For more info about CSS Grid visit https://developer.mozilla.org/en-US/docs/Web/CSS/grid or visit Gridbyexample to see more CSS Grid examples.

About the Author:

CSS Filters: Examples, Use Cases, Caveats

December 21st, 2016

Almost any program, app, or editor that allows you to upload pictures or work with images provides some sort of filter capabilities to be applied to the images. Users of InstagramPhotoshop and Snapseed are familiar with utilizing various filters to create eye-catching images. Well curated images can enhance the appeal of your website and increase traffic to the site. However, creating unique images does not have to be a difficult process or require extraneous tools. CSS includes a filter property which allows you to apply a number of fun and interesting filters to your images. The list of filters include grayscale( ), sepia( ), blur( ), saturate( ), brightness( ), contrast( ), opacity( ), drop-shadow( ), invert( ) and hue-rotate( ). Below is an example of each filter and a description of how it works.

This is the original image to which various CSS filters will be applied.

originallotus

See the Pen GNLKQL by Remi D (@Remi7497) on CodePen.

Grayscale – This filter causes every object in your image to become some shade of gray. Grayscale takes percentage values between 0% and 100% with 0% producing the original image and 100% producing a completely grayscale image. Values in between produce a partially grayscale image. Negative values are not applicable. Note that all filters that take percentage input values, take decimal input values as well.

filter:grayscale(100%)

grayscale

Sepia – This filter produces a sepia image. Like grayscale it takes percentage values of 0% to 100% as input values. 0% results in the original image and 100% is a completely sepia image.

filter:sepia(100%)

sepia

Saturate- This filter saturates the image. It takes percentage values higher than 100%. Higher values result in a more saturated image. A saturation value of 600% is applied to the image below resulting in a bright and vibrant image.

filter:saturate(600%)

saturate600

Blur- This filter blurs the image by the number of pixels specified. The image below is blurred by 2px. A higher pixel value will result in a blurrier image.

filter:blur(2px)

blur

Hue-rotate- The hue-rotate filter takes input values of degrees with 0deg being the lowest possible value and 360deg being the highest possible value. The color is set by rotating the image by the specified number of degrees around the color circle. A rotation of 80deg produces the teal toned image below.

filter:hue-rotate(80deg)

hue

Invert- The invert filter inverts the colors of the image. It takes values between 0% and 100%. A value of 0% produces the original image, while a value of 100% produces an entirely inverted image. The image below is inverted 100%.

filter:invert(100%)

invert

Drop-shadow- The drop-shadow property creates a colored shadow effect behind the image. The values it takes are the x offset, y offset, blur radius and color. Below the x and y offsets are set to 20px, the blur radius is set to 10px and the color is set to teal. Higher values of the blur radius result in a more blurry shadow while lower values result in a sharper shadow.

filter:drop-shadow(20px 20px 10px teal)

dropshadow

Contrast- The contrast filter makes the difference between the dark parts of the image and light parts of the image more distinct. Contrast takes values between 0% and more than 100%. Setting the value below 100% results in a less contrasted image than the original. The higher the value specified the more contrasted the image. As you can see below, setting a contrast of 200% causes the bright parts of the image to become even brighter while the dark parts of the image become darker than before.

filter:contrast(200%)

contrast4

Brightness- The brightness filter also takes values between 0% and more than 100%. A value of 100% results in the original image. Values lower than 100% dims the image while values greater than 100% increases the brightness of the image. The higher the value, the brighter the image. A brightness of 170% is set, resulting in an image so bright that some of the original characteristics become indistinguishable.

filter:brightness(170%)

 bright170

Opacity- The opacity filter controls the transparency of the image. It takes values between 0% and 100% with 0% resulting in a wholly transparent image and 100% resulting in the original image.

filter:opacity(70%)

opacity

Conclusion

Filters are a great way to add unique effects to images. Beautiful images make websites more enjoyable and engaging. The CSS filter property provides ten filters that allow you to enhance the aesthetics of your images. Multiple filters can be combined to provide even more interesting effects not shown in this article. All filters can also be animated giving you more options to create compelling content for your website.

About the Author:

Creating Contrast using CSS

December 21st, 2016

In photography, adjusting the contrast of an image is often an important part of the post processing routine. Contrast refers to the difference between light and dark in an image. In the color spectrum of an image the darkest color possible is black and the lightest color is white. A high contrast image is one that displays a large number of tones between these two extremes. Conversely a low contrast image is one that does not have too much variation between it’s light and dark tones. Images with high contrast tend to be colorful and vibrant whereas images with low contrast tend to be dull and dimmed down.

When speaking of image contrasts another topic that frequently comes up is adjusting the brightness of an image. Modifying the brightness is another way to alter the tones in an image to achieve a specific look. It is possible to adjust the contrast and brightness of an image in CSS. This is done through the filter property. The filter property allows for a range of alterations to be made to images. Two values of the filter property are contrast( ) and brightness( ). Below are examples of how each works.

This is the original image to which we will be applying the contrast and brightness filters.

See the Pen xRexdM by Remi D (@Remi7497) on CodePen.


Contrast

The syntax for contrast is filter: contrast(value); Contrast takes percentage values between 0% to over 100%. A value of 100% results in no change to the image. Values less than 100% reduce the contrast of the image, whereas values greater than 100% increase the contrast of the image. Decimal values are also acceptable as input values. Below are a few examples of applying various contrasts to the image. As you can see at 70% the image is dimmer than the original image. As the contrast is increased the shadows get darker while the highlight tones of the image get brighter.

contrast(70%)                                        contrast(120%)

contrast(150% )                                       contrast(250%)

Brightness

The syntax for adjusting brightness is filter: brightness(value); Brightness like contrast takes percentage values ranging from 0% to above 100%. A value of 100% keeps the original image. Any value less than 100% dims the image, with a value of 0% resulting in a completely black image. Values over 100% increases the brightness of the image. Below is the image at four different brightness levels.

brightness(80%)                                       brightness(130%)

brightness(180%)                                   brightness(250%)

Conclusion

Images are a great way to enhance webpage content and communicate more effectively with users.  The CSS filter property can be used to create bright high contrasted images or dim low contrasted images quickly and easily.

About the Author:

CSS Transforms: Examples, Use Cases, Caveats

December 21st, 2016

CSS transforms allow you to apply a set of changes called transformations to any element. Transforms are implemented using the transform properties transform-origin and transform. The transform-origin property is used to set the origin of the element. If unspecified, the origin is set to be the center of the element. The transform property is used to apply the actual transformations to the element. The values the transform property takes are rotate, scale, translate, skew and matrix. A value of ‘none’ indicates that no transformation should be performed. When an element is transformed in CSS the surrounding elements and document are not affected. Applying transforms to floats therefore is not possible since other elements in the document will not re-adjust in response to the transform action. 2D and 3D transformations are possible in CSS.

2D transforms are simple to implement and several examples are shown below. 3D transforms however require a bit more effort. To use 3D transforms first a perspective must be set which controls how deep or close the user views the 3D transform. After that the transform can be applied to the element. A comprehensive list of all the CSS transforms can be found here.

2D transformations

Below are examples of 2D transformations. To test out any of the code,  copy and paste this code into the editor and change the transform property to what is shown in each example below.

This is the original image to which the transformations will be applied.

original1

See the Pen vyMYBq by Remi D (@Remi7497) on CodePen.

Rotate- As the name implies, rotate allows you to rotate the image a certain number of degrees. The image below is rotated 30 degrees. Positive values rotate the image clockwise while negative values rotate the image anticlockwise.

transform:rotate(30deg);

rotate1

Scale- Scale is used to change the size of the image. It can take one value or two values. Writing scale(10) will increase the image ten times it’s original size. However, writing scale(0.5, 1.12) as shown below will decrease the width by a factor of 0.5 and increase the height by a factor of 1.12. The resulting effect is a stretched looking image.

transform:scale(0.5,1.12);

scale1

Skew- The skew property tilts the image in the x or y direction. As you can see below the image is tilted to the left after a skew of 20 degrees is applied to it in the x direction.

transform:skewX(20deg);

skew1

Translate- The translate property moves the image to the specified length value in the x direction and y direction. The code line below would move the image 20 px to the right and 40 px down.

transform: translate (20px, 40px);

Matrix- The matrix property allows you apply all the transformations at once. It takes six values. If there is a value for which you don’t want a transformation just put a value of 0 for that transform.

transform: matrix(0, 1.2, 0.4, 0.3,0,20);

matrix

3D transformations

Applying 3D transforms requires the additional task of adding perspectives. A perspective morphs the space into a 3D space. The 3D transform allows you to rotate, scale, skew and translate on the X, Y and Z axis. The smaller the perspective value, the more dramatic the effect produced. This is demonstrated in the following example. Below the image is rotated 55 degrees around the X and Y axis at first 100px perspective and then at 50px perspective.

perspective(100px) rotateX(55deg)                    perspective(100px) rotateY(55deg)

100x55                                                            100y55

perspective(50px) rotateX(55deg)                     perspective(50px) rotateY(55deg)

50x55                            50y55

Conclusion

CSS transforms allow you to rotate, skew, scale, and translate elements. Any element can be transformed including text, images, background images and more. CSS transforms can be animated as well. 2D and 3D transformations can be implemented in most recent browsers. The -webkit and -moz prefixes are available for performing transforms in Chrome and Firefox.

 

About the Author:

What Are CSS Pseudo Classes and What Are They Used For?

November 28th, 2016

A CSS pseudo class allows you to assign a specific state to an element. For instance, a user hovers over an image on a web page and it changes to another image. Links change colors once they are visited and can be differentiated from unvisited links. An input box on a form is disabled and does not take a value.  These actions and more are made possible by pseudo classes. Normal CSS classes can also be used with pseudo classes. CSS3 has added more pseudo classes than was previously available in CSS2. A pseudo class is tacked onto a selector. It is preceded by a colon and usually followed by a property with a value in parenthesis. The syntax of a pseudo class is as follows

selector: pseudo-class { property:value;}

Basic Pseudo Classes

There are many different pseudo classes, the code example below demonstrates some of the most basic ones. These are classified as dynamic pseudo classes which change due to the user’s actions. In the code example the :link pseudo class is used to set the color of a link to blue. Once the user has visited the link, the :visited pseudo class is used to change the color of the link to maroon. Also demonstrated is :hover which is used to change the purple circle with white text into a pink square with yellow text when the user hovers over the image. The :focus pseudo class changes the date entry field to gray when the user clicks or “focuses” on it. Copy and paste the code example here to try it out for yourself!

<!DOCTYPE html>

<html>

<head>

<style>

a:link{

   color:blue;

}

a:visited{

  color:maroon;

}

div {

   background-color: purple;

   color: white;

   line-height:90px;

   font-size:20px;

   text-align:center;

   width:200px;

   height:200px;

   -moz-border-radius: 100px;

   -webkit-border-radius: 100px;

    border-radius: 100px;

}

div:hover {

   background-color:pink;

   color:yellow;

   width:200px;

   height:200px;

   -moz-border-radius: 0px;

   -webkit-border-radius: 0px;

   border-radius: 0px;

}

input:focus {

   background-color: lightgray;

}

</style>

</head>

<body>

<p><b><a href="https://appendtonew.wpengine.com/" target="_blank">Click on this link!</a></b></p>

<div>Hover over this</div>

<p><b>Enter todays date in the field below</b></p>

<form>

Date: <input type="text" name="Date"><br>

</form>

</body>

</html>

Some more Pseudo Classes

Listed below are a few more commonly used pseudo classes. A comprehensive list of all the pseudo classes can be found here.

:first-child- This class allows you to add a specific style to elements that are the first child of their parent element.  

:root- This pseudo class is used to match the document’s root element.

:lang- Different languages have differing rules and conventions. Sometimes you need to create pages that are used by multiple languages. The :lang pseudo class is useful for this situation. It looks at mainly the lang=” “ HTML attribute and  <meta> element and matches elements accordingly.  

:disabled- This allows you to indicate disabled input elements such as text fields and buttons.

:fullscreen- Elements that are in full screen mode are used by this pseudo class.

Pseudo Elements

Pseudo elements have similar functionality to pseudo classes in that they can be styled by CSS and are added by user agents. However they are different from pseudo classes because they allow you to work with elements that don’t exist in the DOM. The syntax identifier for pseudo elements is usually double colons instead of the single colon like for pseudo classes. Common pseudo elements are ::before, ::after and ::first-line. It is important to note that some coders use the single colon : for pseudo elements which was the convention in CSS2. Keep this difference in mind to avoid confusion between pseudo classes and pseudo elements.

Conclusion

Pseudo classes make it possible to apply special states to elements. They allow developers to create cool effects without having to use a scripting language such as JavaScript. There are many different types of pseudo classes that allow you to make your page more interactive and fun while keeping the code simple.

About the Author:

Simple, Elegant, Common CSS Animations

November 24th, 2016

CSS animations provides a simple way to create animations for your webpage that does not require complicated coding or a scripting language such as JavaScript.  While CSS’s animation capabilities are not as extensive as JavaScript, there is still a lot that can be done using CSS. CSS animations allows you to transition the style of an element or group of elements over a period of time. How long this duration is and what styles are used is entirely up to the developer. There are just two basic keys to creating a CSS animation. First the element to be animated and it’s properties need to be defined. Also, the animation sub-properties such as animation name, duration and direction need to be defined inside of the element. After that the @keyframes rule which contains the styling properties and values needs to be defined. The @keyframe name is the same as the name assigned to animation-name inside the element. The pseudo code goes something like this:

element_name{

        property:value;

        property:value;

        animation-name: my_animation;

        animation-direction: reverse;

}

@keyframes my_animation{

       from {property:value;}

       to {property:value;}

}

Alternatively, @keyframes can also be used to assign styles at specific times during the animation sequence such as when the animation has started and is 25% of the way through, 50% of the way through and so on. Below is the pseudo-code.

@keyframes my_animation{

     0% {property:value;}

     25% {property:value;}

     50% {property:value;}

     75% {property:value;}

     100% {property:value;}

}

Sub-properties

There are various sub properties of the animation property that allow you to create cool effects. Listed below are the most commonly used ones.

animation-duration- This allows you to define how long one cycle of your animation is.

animation-delay- This allows you to set your animation on a delay. If you have set the delay to be 1 second, the element that is on delay will start and finish 1 second later than the rest of the elements.

animation-iteration-count– This specifies how many times the animation is played. To play the animation indefinitely set this property to infinite.

animation-direction- An animation can have four possible directions, namely normal, reverse, alternate, and alternate-reverse. In normal mode the animation always re-starts each cycle at the same point and plays forward. In reverse it does the same but backwards. For alternate, the animation plays one cycle forward and one cycle in reverse and keeps alternating between the two. Alternate-reverse is the same thing except it starts backwards.

animation-timing-function- This function has a set of predefined values that sets the speed of the animation. The values are ease, linear, ease-in, ease-out, and ease-in-out. There is also a cubic Bezier function that allows you to specify your own values using cubic-bezier(n,n,n,n).

Shorthand Notation

While it is possible to write out each animation property and value, it is not necessary. Instead of writing

animation-name: my_animation;

animation-duration: 5s;

animation-direction: alternate;

You can simply write:

animation: my_animation 5s alternate;

Example

Copy and paste the code below into this editor in order to follow along with the example. In the days of the week animation, five circles with labels that indicate each work day of the week Monday- Friday are animated. First a div element is created that defines the properties of the five circles and their text labels. The animation property is used to set the name to ‘daysoftheweek’, the duration to five seconds, the iteration-count to be infinite and the direction to be alternate. After that the animation timing function ‘ease’ and a specific delay is assigned to each circle. Then the @keyframes rule is written to define which styles the properties will transition into. As you can see in the code several animations are happening simultaneously. Seven properties are defined which change styles in the ‘from’ block and ‘to’ block. The circles are set to move across the page while changing color and shape. The font-size of the text is set to decrease until it disappears as the circle moves across the page. Also the box-shadow is set to transition from visible to invisible.

<!DOCTYPE html>

<html>

<head>

<style>

p{

   font-size:30px;

   font-style:italic;

   text-align:center;

}

div {

   width: 85px;

   height: 85px;

   border-radius:42px;

   background-color: orange;

   box-shadow: 15px 10px 5px #888888;

   font-weight: bold;

   font-size: 30px;

   position: relative;

   animation: daysoftheweek 5s infinite alternate;

}

/*Apply timing function and delay*/

#div1 {animation-timing-function: ease; animation-delay:0.5s}

#div2 {animation-timing-function: ease; animation-delay:1s}

#div3 {animation-timing-function: ease; animation-delay:1.5s}

#div4 {animation-timing-function: ease; animation-delay:2s}

#div5 {animation-timing-function: ease; animation-delay:2.5s}

/* Keyframe */

@keyframes daysoftheweek {

   from {left: 0px; background-color:orange; width:85px; height: 85px;         border-radius:42px; font-size:30px;  box-shadow: 15px 10px 5px #888888;}

   to {left: 300px; background-color:blue; width:50px; height: 50px; boder-     radius:25px; font-size:0px;  box-shadow: 0px 0px 0px #888888;}

}

</style>

</head>

<body>

<p> Days of the Week Animation </p>

<div id="div1">M</div>

<div id="div2">T</div>

<div id="div3">W</div>

<div id="div4">Th</div>

<div id="div5">F</div>

</body>

</html>

Conclusion

CSS animations allows you to create simple, quick animations that enhance the quality of your web page and content. With CSS animations, you can add fun, elegance, and vibrancy to your page without having to learn JavaScript or write difficult, hard to debug code. The animations also work well in almost all browsers. Compatibility issues are rare with CSS animations which is not always the case with animations created in other languages.

About the Author:

What Is CSS Grouping and What Is It Used For?

November 24th, 2016

Grouping in CSS is a technique used to reduce code redundancy and write clean, concise easy to follow code. There are going to be many instances in which multiple CSS selectors will have the same declarations. In these cases, you can group all the selectors together and write the declarations only one time. For example, if you want to apply the exact same font size and color to three different headings you can write it as shown below. However, this is a waste of space.

h1{
 font-size: 10px;
 color: green;
}
h2{
 font-size: 10px;
 color: green;
}
h3{
 font-size: 10px;
 color: green;
}

Instead you can shorten the code by grouping it. Since all three headings have the exact same declarations, you can write the three heading selectors separated by a comma and write each declaration one time reducing three blocks of code to one. The more declarations you have that are the same for different selectors, the more space you can save by condensing it using grouping. Make sure not to put a comma after the last selector as it will render the code block useless.

h1, h2, h3 {
 font-size: 10px;
 color: green;
}

It is important to note that different types of selectors can be grouped with each other. There are three main types of CSS selectors, the element selector, id selector and class selector. The element selector uses element names in order to select the elements. The id selector selects elements by looking at the id attribute of an HTML element. It is denoted with the # character and refers to a unique element within the page. The class selector uses the class attribute to select elements. It is denoted by a period (.) followed by the class name. All three types can be grouped together like so

p, #id_value, .class {
 //Declarations
}

Another tip to keep in mind is that you can group together as many selectors as you want and any valid CSS selector can be part of a group.

Conclusion

CSS grouping can be used to condense code that has multiple selectors with the same declarations. This makes code easy to read and maintain. Also development time is significantly reduced as there is less code to write. Page load times are reduced as well when using grouping. There is no reason not to use grouping whenever applicable.