Dynamic CSS

The fundamentals of CSS transforms, transitions, and animation are the basics that allow front-end developers to kick it up a notch and add a bit more pizazz and interactivity to websites. What are the basic building blocks that make up these capabilities? What is the difference between a transition and a transform? What does browser support look like? Most importantly, how can you put these tools to use in your next project and where can you find good resources to learn more?

I’ve given two talks on this subject and have started to write about it as well. This post will store all of the links to resources I’ve created that explore the basics of how to add some of the more truly dynamic elements of CSS to our websites.

Blog Posts

Slide Decks

HTML Basics: Elements, Tags, and Document Structure

HTML stands for HyperText Markup Language and is the basic structural element that is used to create webpages. HTML is a markup language, which means that it is used to “mark up” the content within a document, in this case a webpage, with structural and semantic information that tells a browser how to display a page. When an HTML document is loaded by a web browser, the browser uses the HTML tags that have marked up the document to render the page’s content.

There are three types of code that make up a basic website page. HTML governs the structural elements, CSS styles those elements, and JavaScript enables dynamic interaction between those elements.

HTML structure + CSS style + JS interaction = web page

Elements and Tags

HTML elements and tags work together to mark up content. HTML elements indicate the purpose of a tag and tags indicate the beginning and the end of an element.

For example, here is a simple paragraph in HTML:

<p>This is a paragraph.</p>

The letter “p” represents the paragraph element. In this example, <p> is an opening tag that tells the browser that the content that follows it is a paragraph. The slash in the second tag, </p>, indicates that it is a closing tag that tells the browser that the paragraph element is ending and that any content that appears after it is not part of the paragraph. You may encounter serious display issues if you don’t remember to “close” each tag because the browser will interpret this pattern as meaning that the element identified by the opening tag should continue for the rest of the page.

element and tag labeled

You can find a full list of all HTML elements at the Mozilla Developer Network HTML Element Reference Page.

Basic HTML Page Structure

A basic HTML page is a document that typically has the file extension .html, though HTML frequently appears in the content of other file types as well. All HTML documents follow the same basic structure so that the browser that renders the file knows what to do. The basic structure on which all webpages are built looks like this:

<!DOCTYPE html>
<html>
    <head>
        <title>Page Title</title>
    </head>
    <body>
        <h1>Homepage Headline</h1>
        <p>This is a paragraph.</p>
    </body>
</html>

When this code is rendered by a browser, it will look like this:

basic html page rendering in the browser

 

Doctype

The first line of code, <!DOCTYPE html>, is called a doctype declaration and tells the browser which version of HTML the page is written in. In this case, we’re using the doctype that corresponds to HTML5, the most up-to-date version of the HTML language. There are a number of different doctype declarations that correspond to various versions of HTML.

HTML Root Element

Next, the <html> element wraps around all of the other code and content in our document. This element, known as the HTML root element, always contains one <head> element and one <body> element.

Head Element

The HTML head element is a container that can include a number of HTML elements that are not visible parts of the page rendered by the browser. These elements are either metadata that describe information about the page or are helping pull in external resources like CSS stylesheets or JavaScript files.

The <title> element is the only element that is required to be contained within the <head> tags. The content within this element is displayed as the page title in the tab of the browser and is also what search engines use to identify the title of a page.

All of the HTML elements that can be used inside the <head> element are:

Body Element

There can only be one <body> element in an HTML document because this element is the container that holds the content of the document. All of the content that you see rendered in the browser is contained within this element. In the example above, the content of the page is a headline and simple paragraph.

Nesting

You might have noticed that I keep referring to HTML elements as “containers.” This is because proper “nesting” is a key part of writing HTML that will work across all browsers, will render all content, will be readable by screen readers, and will be able to be targeted by CSS and JavaScript. In terms of HTML, nesting means exactly what you’d think it might mean: each element goes inside another element, just like nesting dolls are physically “nested” within each other.

For example, the basic page structure we outlined above is valid HTML because each element’s opening tag has a closing tag and fully contain any other elements within it.

I’ve used HTML comments to label the example we’ve been using to show which tags are opening tags and which tags are closing tags, so you can see how each element is nested. In HTML, any content that is in between <!-- and --> is a comment that will not be rendered by the browser.

<!DOCTYPE html> <!-- doctype declaration -->
<html> <!-- opening HTML tag -->
    <head> <!-- opening head tag -->
        <title>Page Title</title> <!-- title tag -->
    </head> <!-- closing head tag -->
    <body>  <!-- opening body tag -->
        <h1>Homepage Headline</h1> <!-- h1 headline -->
        <p>This is a paragraph.</p> <!-- paragraph -->
    </body> <!-- closing body tag -->
</html> <!-- closing HTML tag -->

Keep in mind that indentation is used by developers to help make sure that their HTML is nested properly and to ensure that all opening tags have a corresponding closing tag. Just like HTML comments, the browser will not display indentations in the code, these formatting patterns are there solely to help improve the readability of code.

The following version of the sample code is not nested correctly. Take a moment to look and find the nesting errors here.

<!DOCTYPE html>
<html>
    <head>
        <title>Page Title</title>
    <body>
    </head>
        <h1><p>Homepage Headline</h1>
        This is a paragraph.</p>
    </body>
</html>

There are two nesting errors in the previous example:

  1. The opening <body> tag is contained within the opening and closing <head> tags.
  2. The opening <p> tag in the <body> content is contained within the opening and closing <h1> tags.

This code actually will render in some browsers, but just because something renders doesn’t mean that the code is syntactically correct.

Conclusion

In this post we’ve learned what HTML is, what an HTML element is, what an HTML tag is, and how a basic HTML page is structured. Do you have any questions about any of these concepts? Leave your questions in the comments!

This post is the first in a series of intro to HTML topics inspired by my HTML workshop at the TechLady Hackathon in August, 2015. This post will be updated with links to the other posts in the series as they are published.

 

 

Making Responsive Rectangles and Squares with CSS

The basic conceptual and literal building block of most responsive CSS shapes is the rectangle. In terms of geometry, a rectangle is a parallelogram where each corner is a right angle. This means that once you know how to make a responsive CSS rectangle, you’ll automatically know how to make a responsive CSS square. Always remember: squares are just rectangles where all of the sides are the same length.

Non-Responsive Rectangles

It is really easy to make a non-responsive rectangle using a single div and a just a smidgen of CSS. If you squish your browser window you’ll see that this rectangle has a fixed width and height.

HTML

<div class="fixed-rectangle"></div>

CSS

div.fixed-rectangle {
     width: 400px;
     height: 100px;
     background-color: #ca0164;
}

To make this fixed size rectangle all we need to do is apply a width and height to the .fixed-rectangle class we are using to identify the div. I added a background color so that you can see the rectangle, but remember that background colors aren’t required to actually create the shape itself.

If you were to change the width and height in the CSS for this fixed-size rectangle to percentages, your code wouldn’t work and nothing would render. The reason this will not work is because percentage height is always calculated based on the height of the element and in this case, the height of the element would always be zero. How then can one make a responsive rectangle?

Responsive Rectangles

The key to making a truly responsive rectangle is vertical padding, either padding-bottom or padding-top will work. Why, you might ask? Vertical padding is calculated on the basis of the width of the element. Therefore, when using vertical padding in combination with a percentage width one can maintain an aspect ratio across widths, which is what truly defines a responsive rectangle.

There are a few different ways of making responsive rectangles, but the below code demonstrates my favorite basic method. This code can be extended to incorporate a number of other things, including text.

HTML

<div class="flex-rectangle"></div>

CSS

.flex-rectangle{
    width: 100%;
    background: #ca0164;
}
.flex-rectangle:before{
    content: "";
    display: block;
    padding-top: 25%;
}

So how does this work? The width of the rectangle is established through a percentage width on the selector. I’ve added a background color here as well so that you can actually see the rectangle. Again, a background color is not required for the element to render.

I’ve used the pseudo-selector :before to add the padding to the element. In order for anything to render, the pseudo-selector needs the content property to be included, though you don’t need to (and shouldn’t) include any actual content. The pseudo-selector also needs to be displayed as a block element.

The padding-top property is what governs the height and aspect ratio of the rectangle. Remember that this value is calculated based on the width of the element. In this case I wanted the rectangle to have a 4:1 aspect ratio to match our fixed size example. Therefore, I needed to set the vertical height to a quarter of the width of the element, which is 25% in this case. If the width of the rectangle was set to 80% we’d need to set padding-top to 20% in order to achieve the same 4:1 aspect ratio.

Responsive Squares

Now that we’ve walked through a responsive rectangle, making a responsive square should be easy. All we need to do is make a responsive rectangle with a 1:1 aspect ratio.

HTML

<div class="flex-square"></div>

CSS

.flex-square{
    width: 30%;
    background: #ca0164;
}
.flex-square:before{
    content: "";
    display: block;
    padding-top: 100%;
}

The width of our square is set to 30% and padding-top is set to 100% on the pseudo-element. We have a 1:1 aspect ratio and therefore a square because the height is set to 100% of the width.

Browser Support

This method will work in all modern browsers and in Internet Explorer 9 and above. Remember, Internet Explorer 8 did not support responsive design without some serious hackery, so it makes total sense that responsive shapes would be a no-go in IE8!

CSS Transitions: The Basics

The standard linguistic definition of a transition is a “movement, passage, or change from one position, state, stage, subject, concept, etc., to another.” Within CSS, transitions do exactly what you’d expect: they allow for elements to change from one state to another over time.

My favorite short explanation of what the CSS transition property does is from Chris Coyier of CSS Tricks:

The transition property is a shorthand property used to represent up to four transition-related longhand properties [that] allow elements to change values over a specified duration, animating the property changes, rather than having them occur immediately.

The four properties governed by CSS transitions are:

  • transition-property
  • transition-duration
  • transition-timing-function
  • transition-delay

Syntax

The syntax for CSS transitions allows for all possible transitions to be bundled into one line of code and also allows for the granular specification of each property on its own. Each transition property will accept one of an available set of values whether you are using the shorthand or longhand CSS structure.

Shorthand

transition: <property> <duration> <timing-function> <delay>;

Longhand

transition-property: <property>;
transition-duration: <duration>;
transition-timing-function: <timing-function>;
transition-delay: <delay>;

Transition Property

The aptly named transition-property property specifies which property or properties will be impacted by the transition. The default value for this property is all.

Syntax

transition-property: value;

Accepted transition-property values are:

  • all
  • none
  • single property name
  • multiple property names, separated by commas

Example: Stage 1

This example includes just the transition-property value. For all examples, hover over the smiley box in order to see the active state.

.box {
	transition-property: color, background-color, width;
    	color: #ffffff;
    	background-color: #ca0164;
    	width: 3em;
        height: 3em;
        text-align: center;
} 

.box:hover {
	color: #384042;
	background-color: #F5B54B;
	width: 3.6em;
}

Transition Duration Property

The transition-duration property specifies the amount of time the transition will take. The default value for this property is zero seconds..

Syntax

transition-duration: value;

Accepted transition-duration values are:

  • time in seconds (s) or milliseconds (ms)
  • multiple time values, separated by commas
  • initial
  • inherit

Example: Stage 2

In this example, we’ve added a transition-duration of two seconds in addition to specifying the transition-property value. The transition between the initial state and the active state is now smoother upon hover due to the presence of the transition-duration function.

.box {
	transition-property: color, background-color, width;
        transition-duration: 2s;
    	color: #ffffff;
    	background-color: #ca0164;
    	width: 3em;
        height: 3em;
        text-align: center;
} 

.box:hover {
	color: #384042;
	background-color: #F5B54B;
	width: 3.6em;
}

Transition Timing Property

The transition-timing-function specifies the pace at which the transition will run. The default value for this property is ease.

Syntax

transition-timing-function: value;

Accepted transition-timing-function values are:

  • ease
  • linear
  • ease-in
  • ease-out
  • ease-in-out
  • step-start
  • step-end
  • custom cubic Bézier curve value
  • custom stepping function value

The transition timing function’s possible values are an immensely complex topic. To learn more about them, you should read this amazing article.

Example: Stage 3

In this example, we’ve added the transition-timing-function ease-in-out in addition to specifying values for transition-property and transition-duration. The transition between the initial state and the active state now changes pace midway through due to the presence of the transition-timing-function property value.

.box {
	transition-property: color, background-color, width;
        transition-duration: 2s;
        transition-timing-function: ease-in-out;
    	color: #ffffff;
    	background-color: #ca0164;
    	width: 3em;
        height: 3em;
        text-align: center;
} 

.box:hover {
	color: #384042;
	background-color: #F5B54B;
	width: 3.6em;
}

Transition Delay Property

The transition-delay property specifies when the transition will start relative to the instant the property value changes. The default value for this property is zero seconds.

Syntax

transition-delay: value;

Accepted transition-delay values are:

  • time in seconds (s) or milliseconds (ms)
  • multiple time values, separated by commas
  • initial
  • inherit

Example: Stage 4

In this example, we’ve added the a transition-delay of three seconds in addition to specifying values for transition-property, transition-duration, and transition-timing-function properties. Now, when you hover over the box, the transition between the initial state and the active state takes three seconds to start due to the presence of the transition-delay property value.

.box {
	transition-property: color, background-color, width;
        transition-duration: 2s;
        transition-timing-function: ease-in-out;
        transition-delay: 3s;
    	color: #ffffff;
    	background-color: #ca0164;
    	width: 3em;
        height: 3em;
        text-align: center;
} 

.box:hover {
	color: #384042;
	background-color: #F5B54B;
	width: 3.6em;
}

Browser Support

CSS transitions are supported in all major browsers including Internet Explorer 10 and above. The lack of support for Internet Explorer 9 and below may be a minor roadblock towards implementing transitions in your projects, so make sure you employ CSS transitions with an eye towards graceful degradation. There is one remaining browser prefix required for full cross-browser support (listed below).

Prefix Requirements

  • -webkit-

CSS Transform Origin Property

The CSS transform origin property defines the point from which a CSS transform is applied to an element.

Transform Origin Syntax

The syntax for identifying the value of the transform-origin property takes into account the x-offset and y-offset of the point of origin. The x-offset is a length or percentage from the left edge of the element. Correspondingly, the y-offset is a length or percentage from the top edge of the element.

transform-origin: x-offset y-offset;

The default value for the transform-origin property is the center of an element (50% 50%).

Any unit that can be used to define the length of an element (px, em, rem, percentage) can be used to identify the x-offset and y-offset values of the transform-origin property. Additionally, there are several keywords that are acceptable for use with the transform-origin property:

  • left (0%)
  • center (50%)
  • right (100%)
  • top (0%)
  • bottom (100%)

Examples

For context, the examples included here show a faded version of the box in it’s original position, prior to the transform, behind each transformed element.

Rotate

Rotate 25 Degrees to the Left with Transform Origin at Top Right

.box { 
      transform: rotate(-25deg); 
      transform-origin: 100% 0%;
} 

Rotate 25 Degrees to the Left with Transform Origin at Bottom Right

.box { 
      transform: rotate(-25deg); 
      transform-origin: right bottom;
} 

Scale

Scale to 50% with Transform Origin at Top Right

.box { 
      transform: scale(0.5); 
      transform-origin: 100% 0%;
} 

Scale to 50% with Transform Origin at Bottom Right

.box { 
      transform: scale(0.5); 
      transform-origin: right bottom;
} 

Skew

Skew 25 Degrees to the Left with Transform Origin at Top Right

.box { 
      transform: skewX(25deg); 
      transform-origin: 100% 0%;
} 

Skew 25 Degrees to the Left with Transform Origin at Bottom Right

.box { 
      transform: skewX(25deg); 
      transform-origin: right bottom;
} 

Translate

You’ll notice that when the transform-origin property is applied to a translate transform function that there is no apparent visual difference in the outcome. This is because the element impacted by the transform is moved without changing it’s shape, size, or rotation.

Translate 1em to the Bottom Right with Transform Origin at Top Right

.box { 
      transform: translate(1em, 1em); 
      transform-origin: 100% 0%;
} 

Translate 1em to the Bottom Right with Transform Origin at Bottom Right

.box { 
      transform: translate(1em, 1em); 
      transform-origin: right bottom;
} 

Browser Support

CSS transform-origin is supported in all major browsers including Internet Explorer 9 and above. There are a handful of browser prefixes that are required for full cross-browser support (listed below).

It’s also important to note that though 3d transforms are not yet fully supported, they can be use in quite a few browsers now. With 3d transforms, a third value is accepted through the transform-origin property that represents the z axis.

Prefix Requirements

  • -ms-
  • -webkit-

CSS Transforms: The Basics

Linguistically speaking, a transform is a “change in form, appearance, or structure,” at least according to the folks over at Dictionary.com. When it comes to CSS, the Mozilla Developer Network describes a transform this way:

“The CSS transform property lets you modify the coordinate space of the CSS visual formatting model. Using it, elements can be translated, rotated, scaled, and skewed according to the values set.”

What exactly does this definition mean? In a nutshell, CSS transforms change an element so that it’s form and visual appearance is modified. There are four basic types of CSS transforms that modify an element in different ways: rotate, scale, skew, and translate. Matrix, another type of CSS transform, is an advanced type of transform that is beyond the scope of this post.

Transforms: Syntax

The syntax for applying a CSS transform to an element is the same regardless of the specific transform function you want to use. The transform property allows for multiple transform functions to be included in one line of code. The default value of the transform property is none.

No Transforms

transform: none;

One Transform

transform: <transform-function>;

Multiple Transforms

transform: <transform-function> <transform-function> <transform-function>;

Rotate

The rotate transform function behaves exactly as you expect it will and allows you to rotate an element clockwise from its current position. Counter clockwise rotations can be achieved by using negative values.

Syntax

The specific syntax for a rotation is as follows. Angles are expressed in the format (5deg) or (-5deg), for example.

transform: rotate(angle);

Example

All examples in this post will use the following HTML and CSS to demonstrate the original state of the element before the transformation function has been applied. Any additional sample code will only account for the transform itself.

<div class="box"><i class="fa fa-smile-o"></i>
</div>
.box {
    width: 3em;
    height: 3em;
    background: #ca0164;
    color: #ffffff;
    text-align: center;
}

.box .fa {
    font-size: 2em;
    line-height: 1.45em;
}

Example: Rotate 25 Degrees to the Right

.box {
	transform: rotate(25deg);
}

Scale

The scale transform function does exactly what you’d think it might do and scales an element relative to its original size. The values specified within scale transforms are unitless and should be thought of as a multiplier.

Syntax

There are three different variations on the syntax for the scale transform function since an element can be scaled on the X axis, the Y axis, or on both axes.

X and Y axis Scale

In this format, if only valueX is specified, valueY is assumed to be equal to valueX and the element is therefore scaled proportionately.

transform: scale(valueX, valueY);

Just X axis Scale

transform: scaleX(valueX);

Just Y axis Scale

transform: scaleY(valueY);

Example: Shrink to half size

.box {
	transform: scale(0.5);
}

Skew

The skew transform function shifts  an element along the X and/or Y axis by an angle value.

Syntax

An element can be skewed along the X axis, Y axis, or along both axes, but there are only two valid syntax structures for this type of transform. You’d expect that there would be a compound format similar to that for the scale transform function to address the transform of the X and Y axes in the same function, but that particular structure is no longer in the CSS specification and should not be used.

Just X axis Skew

transform: skewX(angleX);

Just Y axis Skew

transform: skewY(angleY);

Example: Skew left

.box {
	transform: skewX(25deg);
}

Translate

The translate function moves an element vertically and/or horizontally relative to its current position. Positive values will move the element right on the X axis or down on the Y axis. Conversely, negative values will move the element left on the X axis or up on the Y axis. Any generally accepted length value can be used (pixels, ems, etc.).

You might be wondering: Why would you use translate when you can use more established CSS standards for layout and formatting? In general, you should never use the translate function for basic layout needs. Instead, think of translate as a more efficient way to move an element’s placement in a transition or animation.

Syntax

The syntax for the translate transform is nearly identical to the syntax for the scale transform function and accounts for the ability to translate an element along the X axis, Y axis, or both axes.

X and Y axis translation

transform: translate(valueX, valueY);

Just X axis translation

transform: translateX(valueX);

Just Y axis translation

transform: translateY(valueY);

Example: Move Box to Bottom Right

.box {
	transform: translate(3em, 3em);
}

Browser Support

CSS transforms are supported in all major browsers including Internet Explorer 9 and above. There are a handful of browser prefixes that are required for full cross-browser support (listed below).

It’s also important to note that 3d transforms are coming and can be used in a lot of browsers now, but they are only partially supported in IE10 and 11. Once Internet Explorer has more widespread support for 3d transforms, the universe of what is truly possible with CSS transforms will expand even further.

Prefix Requirements

  • -ms-
  • -webkit-

Styling Bulleted Lists with an Icon Font

Though the classic bulleted list is perfectly utilitarian in many circumstances, sometimes we need to present bullets that are a little more graphically variant than the list styles disc, circle, and square. In this tutorial, I’ll walk you through styling bulleted lists using an icon font and CSS to create custom bullets.

Step 1: Install an icon font

We’re going to use Font Awesome as our icon font for this tutorial because it is freely available and has an awesome number of icons available (pun intended). Follow the instructions on their handy getting started page to install the Font Awesome icon font on your site.

You can use whatever font icon set you want to accomplish a similar effect, so Google away if you’d like to find some alternatives. I am also a huge fan of making custom icon fonts using Icomoon.

Step 2: Make a List

To ensure that the styling for our fancy list does not interfere with the styling of any other lists that appear on the page, I’m going to give our list a class of “fancy-list.”

The Code


<ul class="fancy-list">
<li>list item one </li>
<li>list item two </li>
<li>list item three </li>
</ul>

Output

  • list item one
  • list item two
  • list item three

Step 3: Remove the Standard Bullets

Now we need to remove the default bullet styling. We’ll do this by setting the list-style to “none” in our CSS. Additionally, I am adding some basic text formatting to govern the font and font size of the list text.

The Code


ul.fancy-list {
font-family: arial, sans-serif;
font-size: 16px;
line-height: 20px;
list-style: none;
}

Output

  • list item one
  • list item two
  • list item three

Step 4: Add the Icon Bullets

We are going to use the CSS pseudo-class :before and the content selector to place a star icon () before each list item.

To do this, we need to call the unicode key for the icon you want to use through the content selector. You’ll need to place a backslash (not a forward slash) before the unicode key in order for the character to render properly in the browser. In our example, the unicode key for the star character in the Font Awesome family is f005. You can find the unicode information for each Font Awesome icon on this cheat sheet or on the page for each individual icon.

In order for our icon to actually appear, we also need to define the icon font to be the font family for the pseudo class content. In this case, the font name is FontAwesome. I am also defining a color to make our stars orange.

The Code


ul.fancy-list li:before {
font-family: FontAwesome;
content: "f005";
color: #F5B54B;
}

Output

  • list item one
  • list item two
  • list item three

Step 5: Adjust Icon Size

Things are starting to look pretty good, except for the fact that our star is out of proportion to the text in our list. We’ll adjust the size of the icon by using font-size, just like we would to style the size of any other font.

The Code


ul.fancy-list li:before {
font-family: FontAwesome;
font-size: 9px;
content: "f005";
color: #F5B54B;
}

Output

  • list item one
  • list item two
  • list item three

Step 6: Adjust Spacing

We’re almost there! Now we just need to adjust the spacing so that there is some space between the star and the text and so that the star is vertically centered to align with each line of text.

Adding margin-right: 5px; adds the space we need between the star and the text.

Addressing the vertical centering of the star is a bit more tricky. You might think that adding padding-bottom or margin-bottom would work, but this actually adjusts the vertical placement of each list item AND the star. In order to control the placement of the star independently, we need to set position: relative;. Then, we can set the bottom property to whatever value places our stars in the right place.

The Code


ul.fancy-list li:before {
font-family: FontAwesome;
font-size: 9px;
content: "f005";
color: #F5B54B;
position: relative;
margin-right: 5px;
bottom: 2px;
}

Output

  • list item one
  • list item two
  • list item three

Conclusion

Pulling in font icons through CSS is one way I’ve discovered to create consistent and graphically variant styling of bulleted lists. This technique is flexible across pretty much any icon font, including those you create yourself. Best of all, this technique is supported in modern browsers (though you may come across some issues with IE8).