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:

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.

About the Author:

3 Ways to Center in CSS

November 16th, 2016

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

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

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

Individually,

1. Padding

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

padding = (outer - inner) / 2

or

p = (o - i) / 2

Using the example values from above the formula yields

75 = (200 - 50) / 2

or

75px

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

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

2. Transform

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

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

3. Flex

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

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

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

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

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

Hopefully you found this article helpful. Thanks for reading!

About the Author:

A Simple Guide to CSS Media Queries 

November 10th, 2016

Media types were originally introduced in CSS2 as the @media rule. The original idea was to have the ability for different style rules to be applied across different devices. For example, there would be style rules for computers, another one for printers and then smartphones, tablets, and more. These didn’t get picked up and put into widespread use. To counteract that, media queries were introduced in CSS3.

Media queries allow the code to look at the capability of the device rather than what type of device it is.

CSS3 media queries will check to see the width and height of both the device and viewing screen. They also also take into account orientation. The device will either be in landscape mode or portrait (resolution is also considered). The technique is a popular way to supply style changes across different sized devices.

Media Query Syntax

With a couple lines of code, you can style a webpage easily between multiple screen sizes. The properties that will be highlighted and changed across devices include some of the following: width, height, float, and margins.

The media query consists of a few different elements in its syntax. It can contain one or a couple expressions and can return true or false.

@media not / only (type of media) and (expressions) {
    /* CSS Style elements. */
}

Once a query goes through and is rendered true, meaning it has been applied on a new device with new dimensions and so on, it will display the specified media types for the new device. The corresponding style changes and rules will be applied following all other CSS rules. The not or only operators will imply the changes to made when they become necessary. Here is a list of some of the media types:

Once a query renders true, it will be applied on the new device. The corresponding style changes and rules will follow all other CSS guidelines Here is a list of some of the media types:

  • Value: used to describe the element.
  • All: media used across all types of devices.
  • Print: media used for printers.
  • Screen: Used for varying tablet screens, computers, smartphones, and more.

Media Queries Examples

It’s time to take the skeletal structure of the media query and apply some real expressions and media types to it. Here are a few examples.

 @media screen and (min-width: 750px) 
{
    #leftsidebar {width: 100px; float: left;
    #main {margin-left:200px;}
}

The previous example will take a webpage’s menu and then shift that to the side if the minimum width of a the screen is 750px, (iPhone 6). It will float to the left and if it is above the minimum width then the menu will stay on the top of the page.

An additional example will highlight the difference in background color on varying devices.

@media screen and (min-width: 480px) {
    body {
        background-color: blue;
    }
}

Overall, CSS Media queries are essential for displaying style aspects from one device to another. There is no need for changing the base CSS code. Developers only need to add this new code to be used when a page is displayed on a new device.