Refactoring HTML and CSS

This article was originally posted at https://christinatruong.medium.com/refactoring-html-and-css-69de73a5fb88 and was kindly shared by Christina Truong. Check out more of her work at https://christinatruong.com.

(Prefer to watch a video? This article is a companion piece to my Decoded by Christina series on YouTube.)

Refactoring is the process of rewriting and restructuring the code to improve the design of the code base. This practice can be applied to any language but this article will focus on HTML and CSS. When refactoring, here are some goals to keep in mind:

Rewrite to reduce complexity. It’s easy to fall into the trap of over-engineering, especially when you’ve just learn a cool new trick. But try to keep in mind to only add what you need.

Make it reusable. Being able to reuse snippets of code means less code overall and more consistency.

Think about how you can make it flexible. This can help to make it easier to reuse and extend features by adding onto existing code snippets.

Make the code easy to read. Use whitespace, indentation and comments for organization. Show your intent by using descriptive class names and comments. Write your code as if you are writing it for someone else to understand. And in some cases you probably are! And even if you are only writing it for yourself, it’s not unusual to come back to a project months later and feel like you have to re-familiarize yourself with the codebase again.

Let’s take a look at some ways to refactor HTML and CSS.

Reduce HTML markup

Something that happens often when adding content and styles to our web projects is inadvertently using too much HTML markup. For example, the <div> element is often used to group or wrap elements to add CSS to them. But it’s not always necessary to throw a <div> around the element that needs to be styled. Every HTML element is its own box and can be styled. In this example, the CSS style will look the same whether you add it to the <h1> element or its container element.

Refactoring HTML and CSS

Refactoring HTML

Create rules for writing CSS

rules for writing CSS

I always start with the base CSS, which are styles that are applied globally. Then add more specific styles as needed. When I say global CSS, I’m referring to the styles that are applied to all or most of the elements on the page, such as the font-family, defining font colors, general margin and padding styles and font sizes. These global styles are applied to the basic type selectors such as body, headings and links. Then get more specific as needed by applying styles using CSS classes. Even then, start with the more generic class styles like page wrappers and page layout styles.

writing CSS

As the project progresses, CSS styles can be added into related groupings such as the header and footer or specific page content, to keep things organized and easy to find.

more CSS

and more CSS

Reduce repetitive code

Combining selectors

Combining selectors

Create reusable classes

Create reusable classes

inheritable CSS styles

Reduce CSS specificity

Reduce CSS specificity

See the Pen
Reduce specificity
by Christina Truong (@christinatruong)
on CodePen.0

Reduce CSS specificity

Do you need to select links, in a “submenu,” in a nav? If so, then use:

If you need to select only links in a “submenu” that specifically uses an ordered list, then use:

But if you just need all the links in any submenu, use the most direct and simple way to get there:

Animating HTML Links with CSS Transition

This article was originally posted at https://christinatruong.medium.com/animating-links-on-hover-with-css-transition-e73b955f1e98 and was kindly shared by Christina Truong. Check out more of her work at https://christinatruong.com.

The CSS transition property does what it sounds like; it creates transitions! But more specifically, it controls the animation speed when changing a CSS style from one state to another. For example, changing the text color when hovering over alink. The hover is the state change.

Prefer to watch a video? This article is a companion piece to my Decoded by Christina series on YouTube.

Changing the state of an element usually requires some kind of user interaction like scrolling down the page or clicking on an object. Making changes based on user interactions usually requires JavaScript. But there is a way to create CSS-only interactions using pseudo-classes.

UNLIMITED DOWNLOADS: 1,500,000+ Icons & Design Assets


CSS pseudo-classes

A CSS pseudo-class is a special keyword, added to a selector, to define a specific state of an element. A common example is using :hover to change the style of a link when a user hovers over it with their mouse.

A common style convention for the link/hover interaction is to change the underline and/or the color styles. By default, links are blue and underlined.

CSS transitions - default link style

But that can be changed with the text-decoration-line and color properties. In the following example, the underline is removed and the default color has been changed.

.link {
  text-decoration-line: none;
  color: crimson;
}

CSS transitions - styled link

Then, using the :hover pseudo-class with the .link class, the underline can be added back in by setting text-decoration-line to underline. To add multiple styles, just add another property to the declaration block. For example, we can also change the color of the text, on hover, by using the color property here. Or change the color of the underline with the text-decoration-color property.

.link {
  text-decoration-line: none;
  color: crimson;
}
.link:hover {
  text-decoration-line: underline;
  text-decoration-color: green;
  color: mediumpurple;
}

Now when you hover over the link, the underline and color changes will be applied instantaneously.

CSS transitions - styled example

You could also do the reverse and leave the underline as is, then remove it on hover. It’s up to you!

text-decoration shorthand syntax
text-decoration-line and text-decoration-color can also be declared using the shorthand text-decoration property.

/* longhand syntax */
.link {
  text-decoration-line: none;
  color: crimson;
}
.link:hover {
  text-decoration-line: underline;
  text-decoration-color: green;
  color: mediumpurple;
}
/* shorthand syntax */
.link {
  text-decoration: none;
  color: crimson;
}
.link:hover {
  text-decoration: underline green;
  color: mediumpurple;
}

The transition property

These types of hover style are a pretty common way of indicating to the user that this bit of text is a link. For these types of interactions, I like to use the transition property to make the change between the styles a little more subtle.

In the following example, the transition style has been included in the CSS. Now, when you hover over the link, the color of the text will change slowly, as it transitions from the one color to another.

See the Pen
Animating with CSS transition
by Christina Truong (@christinatruong)
on CodePen.0

But there is no gradual change showing for the underline style. It displays right away, on hover, just like it did before the transition style was added. That’s because not all CSS properties are affected by the transition property. Let’s dive a little deeper into how this works.

transition is actually shorthand for four sub-properties.

/* shorthand */
transition: color 1s linear 0.5s;

/* longhand */
transition-property: color;
transition-duration: 1s;
transition-timing-function: linear;
transition-delay: 0.5s;

The transition-property and transition-duration must be defined for this style to work. Defining the transition-timing-function and transition-delay are optional.

How to use the transition property
Whether you’re using the longhand or the shorthand syntax, the transition property should be added to the element before the changes start.

In the following example, the hover effect triggers the change. So, the transition property should be added to the .link class, to define the behavior before the changes begin. The styles added to .link:hover are the styles that should be displayed at the end of the transition.

.link {
  text-decoration-line: none;
  color: crimson;
  transition: color 1s linear 0.5s;
}
.link:hover {
  text-decoration-line: underline;
  text-decoration-color: green;
  color: mediumpurple;
}

transition-property

The transition-property determines which CSS style will be applied by specifying the property name (e.g. color or font-size). Only the properties defined here will be animated during the transition.

/* transition will be applied only to 'color' */  
transition-property: color;

/* transition will be applied only to 'font-size' */  
transition-property: font-size;

To apply a transition to more than one property, the values can be separated by a comma or use the keyword all to apply the effect to all the properties that can be transitioned.

/* Transition will be applied to 'color' and `font-size` */  
transition-property: color, font-size;

/* Applied to all properties that can transition */  
transition-property: all;

As we saw in the previous example, some properties can’t be transitioned. If the property has no in-between state, transition can’t be used to show a gradual change.

Referring back to the previous Codepen example, text-decoration-line will not be transitioned. Either the line is there or it isn’t. But the color property does have in-between values, that the browser can define, as it’s changing from one color to another. And by default, the color of the underline follows the color of the text. So while the underline shows right away, the color of the line will transition, on hover.

To see a full list of which CSS properties can be transitioned, check out this resource from the Mozilla Developer Network.

There are alternative ways to create a style that looks like the underline is expanding from left to right but that involves using other properties instead of text-decoration. Check out this article for more details.

transition-duration

The next step is to set the length of time to complete the change, using the transition-duration property. Set the value using seconds with the s unit or milliseconds with the ms unit. You can use whole numbers or decimals. The 0 before the decimal point is not required but can be added, if that is your personal preference.

transition-duration: 1s; /* one second */
transition-duration: 1000ms; /* one thousand milliseconds = 1 second */
transition-duration: 0.5s; /* half a second */
transition-duration: 500ms; /* 500 milliseconds = half a second */

transition-timing-function

The transition-timing-function property is used to set an acceleration curve of the transition, by varying the speed over the duration of the change from one style to the other. It can be used with a variety of keyword or function values.

The keyword values are based on Bézier curves, specifically cubic Bézier curves, which uses four points to define the acceleration pattern.

cubic Bézier curves

/* Keyword values */
transition-timing-function: linear;
transition-timing-function: ease-in;

The linear keyword will set the acceleration pattern to an even speed for the duration of the animation. The ease-in keyword, which is being used in the previous Codepen example, will set the acceleration to start slowly—easing in. Then, the speed will increase until it’s complete.

You can also create your own acceleration patterns, using this function values instead.

/* Function values */
transition-timing-function: steps(4, jump-end);
transition-timing-function: cubic-bezier(0.1, 0.7, 1.0, 0.1);

Personally, I keep it simple when using this property and generally stick linear or one of the ease keywords. Though, the more advanced options would be useful for creating more advanced animations.

Check out the Mozilla Developer Network for a full list of keyword values, examples and more information about creating your own functions.

transition-delay

The transition-delay property can be used to delay the start of the animation. It is defined with seconds or milliseconds.

A positive value will delay the start of the transition. A negative value will begin the transition immediately but also partway through the animation, as if it had already been running for the length of time defined.

This property is also optional and if it’s not declared, there will be no delay at the start of the animation. You can refer to my YouTube video to see a demo of this effect.

Since transition-delay and transition-duration both use the same type of values, when using the shorthand syntax, the first number value will always be read by the browser as the transition-duration value. So make sure to add the transition-delay value after.

/* shorthand */
transition: color 1s linear 0.5s;

/* longhand */
transition-property: color;
transition-duration: 1s;
transition-timing-function: linear;
transition-delay: 0.5s;

And that’s it! Take some time to experiment with these different values and different properties to find the perfect combination for your transitions.

How to create animations using only CSS and @keyframes

This article was originally posted at https://christinatruong.medium.com/how-to-create-animations-using-only-css-and-keyframes-9b282289e70 and was kindly shared by Christina Truong. Check out more of her work at https://christinatruong.com.

Adding dynamic elements to your website usually requires JavaScript. But the animation property and the @keyframes rule can be used to add animation effects using only CSS!

Prefer to watch a video? This article is a companion piece to my Decoded by Christina series on YouTube.

Your Web Designer Toolbox
Unlimited Downloads: 500,000+ Web Templates, Icon Sets, Themes & Design Assets


What is @keyframes?

Before we get too deep into the animation properties, let’s take a step back and talk about how to create the actual animation itself. CSS properties are used to define styles. CSS at-rules are statements used to provide CSS instructions.

For animations, the @keyframes rule is used to define the sequence of the animation and which styles are to be animated.

Let’s look at an example. Below is a website I created for my podcast. It’s a pretty basic page so I wanted to add a little something to it. I used the same five colors, seen in the cassette tape in the logo, as the page’s background colors. With @keyframes I was able to cycle through the colors and make them fade between each change, on a continuous loop.

How to create animations using only CSS and @keyframes

Previously, I’ve talked about using the transition property to animate style changes. But transition only allows you to have a start and end point. So in this example, I would have only been able to transition between two colors: one at the start and one at the end.

With @keyframes, more complex effects can be created by setting multiple points for your animations, which in this case, allows me to use as many colors as I want.

How to use @keyframes

To create this effect, start with the @keyframes keyword.

@keyframes

Then, name the animation with a unique identifier. I recommend choosing something descriptive. Instead using a generic name like “myAnimation” choose a name that describes what you’re creating. This can help you clearly see what the animation is being used for, just by looking at the name.

In my example, my animation effect was used to change the background color. So I could name that animation “colorChange” or “bgColorChange” to make it more specific.

@keyframes bgColorChange

Just like CSS class and ID names, the animation name cannot contain spaces. It can be written as one word or use a dash, underscore or camel casing to separate the words.

@keyframes bgcolorchange
@keyframes bg-color-change
@keyframes bg_color_change
@keyframes bgColorChange

These identifiers are case sensitive so each of these example names would be rendered as different names. So pick a style and be consistent. For me personally, I like to use dashes for my CSS class names and camel casing for @keyframes animation names.

Next, add the left and right curly brackets to contain the animation sequence and style rules.

@keyframes bgColorChange {

}

Then, define the sequence for the animation by using percentages or keywords. Since I have five colors to cycle through, I will need five animation points in my sequence. The start and end points are defined as 0% and 100%. Each will also be followed by a pair of curly brackets.

@keyframes bgColorChange {
  0% {}
  100 % {}
}

This step not only defines the interval points, it is also where the style rules will be added.

The keywords from and to can also be used instead of 0% and 100%.

@keyframes bgColorChange {
  from {}
  to {}
}

But I’ll stick with percentages for this example since I’ll need more keyframes to animate between all five colors. The remaining percentages can be set at 25%, 50% and 75%. Now I have 5 even animation intervals for each color change in my sequence.

@keyframes bgColorChange {
  0% {}
  25% {}
  50% {}
  75% {}
  100 % {}
}

Since I only want the background color to change, I’ll use the background-color property. Just to make it easier to read for this example, instead of using the hex code values for my podcast brand colors, I’ll use similar color keywords for the demo: red, orange, yellow, green and blue. The style declarations added to each interval will be add using the same syntax that you would normally use to declare any other CSS styles.

@keyframes bgColorChange {
    0% { background-color: red; }
   25% { background-color: orange; }
   50% { background-color: yellow; }
   75% { background-color: green; }
  100% { background-color: blue; }
}

It’s usually convention to put the curly brackets on their own line and the style rules in between. But when I’m only using one property, I like to leave it on one line. This is just a personal preference. It’s totally up to you.

selector {
  property: value;
  property: value;
}
selector { property: value; }

At this point, you won’t actually see any animations just yet because this part only creates the sequence. It still has to be initiated and defined using the animation property.

The animation property

animation is actually shorthand for eight sub-properties. Let’s take a closer look at each one.

animation-name
In the example, I want to apply the background-color changes to the whole page, so the style rule can be added to the body selector. The value of the animation-name property is the name of the @keyframes sequence created in the previous step. This is how the animation will be initiated.

body {
  animation-name: bgColorChange;
}
@keyframes bgColorChange {
    0% { background-color: red;}
   25% { background-color: orange; }
   50% { background-color: yellow; }
   75% { background-color: green; }
  100% { background-color: blue; }
}

animation-duration
One more property is still needed to be able to actually see the animation in action: animation-duration. This property is used to set the length of time it will take for the animation to complete one cycle. The value is set using the s unit for seconds or ms for milliseconds. It can be define with whole numbers or decimals.

animation-duration: 2s; 
animation-duration: 2000ms; 
animation-duration: 0.5s; 
animation-duration: 500ms;

If the animation-duration for the background color change example is set to 10s, it will take 10 seconds (2 seconds for each color) to complete one cycle.

body {
  animation-name: bgColorChange;
  animation-duration: 10s;
}
@keyframes bgColorChange {
    0% { background-color: red;}
   25% { background-color: orange; }
   50% { background-color: yellow; }
   75% { background-color: green; }
  100% { background-color: blue; }
}

Only animation-name and animation-duration are required to initiate and run the animation. But you may find that you will need to add some additional style rules.

If you want to follow along with the remainder of the examples, you can follow along with my CodePen example here.

animation-fill-mode
At the end of the example animation, the background color shows the default white background color. That’s because the animation only runs once. So when it’s done, there are no more colors to transition into.

The animation-fill-mode property can be used to control how a CSS animation is applied before and after its execution.

If I wanted the animation to hold onto the last color (blue), I can define this property using the keyword forwards to instruct the animation to retain the last keyframe value. Now, when the animation finishes, the browser will show the blue background color instead of the default white.

body {
  animation-name: bgColorChange;
  animation-duration: 10s;
  animation-fill-mode: forwards;
}
@keyframes bgColorChange {
    0% { background-color: red; }
   25% { background-color: orange; }
   50% { background-color: yellow; }
   75% { background-color: green; }
  100% { background-color: blue; }
}

To see all the available keyword values, refer to the MDN documentation.

animation-iteration-count
What if you want the animation to run more than once? You can do that with animation-iteration-count. This property is used to set the number of times an animation sequence will be played. Number values can be used to define the amount of times the sequence should run, or use the keyword infinite to set the animation to repeat forever.

/* <number> values */
animation-iteration-count: 4;
animation-iteration-count: 1.5;

/* Keyword value */
animation-iteration-count: infinite;

For the background color change, if the animation is set on an infinite loop, then we’ll no longer need the animation-fill-mode property because the animation now runs more than once.

animation-delay
Animations also start right away, as soon as you load the page. So if you want it to start later, use the animation-delay property to specify the amount of time to wait before beginning the animation. This property can also be defined using seconds or milliseconds. You can also use a negative number to start the animation partway through.

animation-delay: 3s;
animation-delay: 250ms;
animation-delay: -2s;

If you set the animation-iteration-count to infinite, any value declared with animation-delay will only be applied to the first iteration of the animation. When the animation loops, there will be no delay.

animation-direction
The animation-direction property is used to set the direction of the sequence.

normal is the default, which shows the animation playing in a forward cycle.
reverse will play it backwards.
alternate will play it forwards first, then play it backwards and alternate.
alternate-reverse will play it backwards first and then alternate.

If this property is applied to the background color example, it will change the direction of the color changes. For example, instead of cycling from red to blue and starting again at red, alternate will play it from red to blue then back to red and so on.

Try adding this property to the CodePen with the different values and see how it changes.

animation-play-state
The animation-play-state will allow you to pause or run the animation. This property is probably most useful when creating some kind of animation that requires user interaction.

animation-play-state: paused;
animation-play-state: running;

animation-timing-function
And the last one, animation-timing-function determines how the animation will progress through the cycle. Different values can be declared to vary the speed over the duration of the change from one style to the other. The keyword values are based on Bézier curves, specifically cubic Bézier curves, which uses four points to define the acceleration pattern.

For example, the linear keyword will animate at an even speed. ease-in-out will animate the property slowly at the beginning, speed up, then slow down at the end.

animation-timing-function: linear;
animation-timing-function: ease-in-out;

animation-timing-function can be used with many more keyword or function values, to create your own acceleration patterns. These values is very similar to the transition-timing-function property that I covered in a previous post about animation with the transition property. You can check out that video or post to see more about how these values work or view the examples in the MDN documentation.

Using animation and @keyframes with multiple styles

In the example I’ve been using so far, I’ve only created an animation with one CSS property, the background-color. But you can also animate multiple CSS properties at the same time. Let’s take a look at another example. This animation will create a bounce effect.

Right now, the setup is similar to the previous example, the background color is changing between keyframes: lightblue at the beginning and lightgreen at the end.

.circle {
  width: 150px;
  height: 150px;
  background-color: lightblue;
  border-radius: 50%;
  position: absolute;
  animation: bounce 1.5s ease-out 1s 10;
}
@keyframes bounce {
  0% { 
    background-color: lightblue;
    /* top: 0px; */
  }
  50% { 
    /* top: 250px; */
  }
  100% { 
    background-color: lightgreen;
    /* top: 0px; */
  }
}

To create a bounce effect and make it look like the circle in bouncing up and down, in addition to the color change, move the the circle up and down.

The position property is set to absolute in the .circle class declaration block, since that style won’t change. But in the @keyframes declaration, the top property will be used to change the position of the circle.

Though we can use multiple properties, the animation itself can only be applied to the same property. So if I want to move this circle down the page, I can’t start with top: 0; and move it to bottom: 0; because top and bottom are different properties. But, the element can be moved down by declaring a new top value. Here’s how:

  • Start with a value of 0px, so it can display at the top of its container.
  • At the 50% keyframe, set the value to 250px (or whatever number you want to reposition the circle to where you want it to be displayed).
  • At 100%, set the value back to 0px to move it back to the top of the container.
.circle {
  width: 150px;
  height: 150px;
  background-color: lightblue;
  border-radius: 50%;
  position: absolute;
  animation: bounce 1.5s ease-out 1s 10;
}
@keyframes bounce {
  0% { 
    background-color: lightblue;
    top: 0px;
  }
  50% { 
     top: 250px;
  }
  100% { 
    background-color: lightgreen;
    top: 0px;
  }
}

This will give the appearance of a bounce effect because it starts at the top of the container, moves 250px down halfway through and then ends back up at the top. Now the position and the background color of the circle is being animated at the same time.

See the Pen
animation with multiple properties
by Christina Truong (@christinatruong)
on CodePen.0

Using the animation shorthand property

In the bounce effect example, I used the shorthand animation property.

animation: bounce 1.5s ease-out 1s 10;

Here’s how it would look using the longhand properties:

animation-name: bounce;
animation-duration: 1.5s;
animation-timing-function: ease-out;
animation-delay: 1s;
animation-iteration-count: 10;

When using the shorthand animation property, order matters when defining the animation-duration and animation-delay values.

Both use the same type of number values, so the first will always be assigned to the animation-duration. If there is a second

I generally recommend using shorthand whenever possible, to make your CSS more efficient. The less you write, the better. But if it makes more sense to use the longhand properties, especially if you’re still getting used to writing CSS, then use the longhand syntax. You can always re-write it later.

Or, what I like to do is use the shorthand property, but add a comment.

Since all these properties begin with animation, I just use the second part of the property name to make the comment shorter. I also separate the values with the pipe character, which is this vertical line. This comment is just a note for yourself so you can format however you like.

/* name | duration | timing-function | delay | interation-count  */
animation: bounce 1.5s ease-out 1s 10;

In case you missed it, the links to the Codepen examples used in this tutorial can be found here and here. To see a more detailed breakdown of the techniques mentioned in the article, check out the corresponding video.

How to Use Different CSS Color Values (RGB, Keywords, HSL)

This article was originally posted at https://christinatruong.medium.com/how-to-use-different-css-color-values-rgb-keywords-hsl-a6b09dc1061 and was kindly shared by Christina Truong. Check out more of her work at https://christinatruong.com.

One of the properties that are used quite often in CSS is color. It can be used with many different types of values such as RGB, HSL and keywords.

Prefer to watch a video? This article is a companion piece to my Decoded by Christina series on YouTube. Or refer to the Codepen snippet to follow along with the examples.

UNLIMITED DOWNLOADS: 500,000+ WordPress & Design Assets

Sign up for Envato Elements and get unlimited downloads starting at only $16.50 per month!



RGB color values

RGB values are defined according to its red, green, and blue components. There are two types of RGB values: hexadecimal and functional.

Hexadecimal RGB values

Hexadecimal RGB values, or hex for short, begin with a number sign followed by six characters, using a combination of numbers from 0–9 and the letters A-F. The first two values represent the red component, followed by the green and blue component values. 0 represents black, F represents white. All other colors are a combination of the numbers and letters.

color: #rrggbb;
color: #000000; /* black */
color: #ffffff; /* white */
color: #ff0000; /* red */
color: #00ff00; /* green */
color: #0000ff; /* blue */

The letters in the hexadecimal notation are case-insensitive so whether you use all lowercase, uppercase or both, they will be read as the same color by the browser.

color: #ffffff;
color: #FFFFFF;
color: #FFFfff;

The hex value can also be abbreviated if the RGB pairs are the same letters or numbers. For example, #f00 is the same color as #ff0000 and #000000 is the same as #000.

color: #f00;    /* shorthand */
color: #ff0000; /* longhand */

color: #000;    /* shorthand */
color: #000000; /* longhand */

Functional rgb() values

The functional rgb() value is defined by using 3 comma-separated numbers between a set of parentheses. The numbers range from 0 to 255 or a percentage between 0-100% to represent the red, green and blue color channels.

color: rgb(0, 0, 0);          /* black */
color: rgb(0%, 0%, 0%);       /* black */

color: rgb(255, 255, 255);    /* white */
color: rgb(100%, 100%, 100%); /* white */

color: rgb(0, 128, 0);        /* green */
color: rgb(0%, 50%, 0%);      /* green */

The spaces between the commas are not a requirement but can be added for readability.

color: rgb(0, 0, 0);
color: rgb(0,0,0);

An optional alpha channel can also be added by using the rgba() function instead. This fourth value is defined with a number between 0 and 1, or a percentage between 0 to 100% to change the opacity level and add transparency to the color.

color: rgba(r, g, b, a);
color: rgba(0, 0, 0, 0);     /* black with 0% opacity */
color: rgba(0, 0, 0, 0.5);   /* black with 50% opacity */
color: rgba(0, 0, 0, 1);     /* black with 100% opacity */

Keyword color values

Another color value type are keywords which are predefined values and include most basic colors like red, black, or yellow. But there are also other keywords that may not immediately come to mind such as lavenderblush or skyblue.

So how do we know which keywords are valid?

One place to find all the keyword values is in the official W3C documentation, which is the organization is responsible for developing the web standards. But it’s pretty barebones in terms of visuals so I usually go to another website I’ve mentioned before in other posts: colours.neilorangepeel.com. You can sort by different color categories and see their corresponding rgb values.

color: red;
color: #FF0000;
color: rgb(255,0,0);

color: lime;
color: #00FF00;
color: rgb(0,255,0);

color: blue;
color: #0000FF;
color: rgb(0,0,255);

All keywords have a corresponding RGB value but there are a finite number of keywords. So using RGB values will provide a wider range of color options.

HSL color values

Another functional color value is hsl() which defines a color by its hue, saturation, and lightness.

The hue is specified as an angle within the color wheel, relative to red. So that means the color red is equal to 0° or 360° while all the other colors are spread around the circle/color wheel. For example, green equals 120°, blue equals 240° and so on.

CSS color values (hue)

Saturation and lightness are represented by the second and third value and are defined using percentages.

  • 100% is full saturation, and 0% is a shade of gray
  • 100% lightness is white, 0% lightness is black

The hue can be defined with or without the degree unit but the saturation and lightness is defined with a percentage.

hsl(270, 60%, 70%)
hsl(270deg, 60%, 70%)

An optional alpha channel component can also be added using the hsla() function to add a fourth value, represented as a number between 0 and 1 or a percentage. 1 or 100% is full opacity.

hsla(270, 60%, 50%, .15)
hsla(270, 60%, 50%, 15%)

Resources

These different types of color values can be found in image or graphics editing software like Photoshop and Illustrator or with online platforms like Canva.

There are also online tools such as CSS Tricks HSLa Explorer and coolors.co for inspiration and to generate color palettes. randoma11y.com is another great resource for creating high contrast color combinations for those with color blindness.

In case you missed it, the links to the Codepen examples used in this tutorial can be found here. To see a more detailed breakdown of the techniques mentioned in the article, check out the corresponding video.

Intro to HTML and CSS

This article was originally posted at https://medium.com/@christinatruong/the-text-shadow-css-property-d1064bb1b27d and was kindly shared by Christina Truong. Check out more of her work at https://christinatruong.com.

In the early days of web development, it wasn’t uncommon for one person to do everything. The job title was often referred to as “webmaster,” “web designer,” or “web developer.” These days, there is often more specialization because the web has become so much more advanced. The different areas of focus are usually broken down into three categories: front-end, back-end, and full-stack.

UNLIMITED DOWNLOADS: 500,000+ WordPress & Design Assets

Sign up for Envato Elements and get unlimited downloads starting at only $16.50 per month!



 

Prefer to watch a video? This article is a companion piece for my Decoded by Christina series on YouTube.

Front-end vs Back-end vs Full-stack

Front-end

Front-end developers work with browser based languages: HTML for displaying content, CSS for adding styles and JavaScript for interactivity. With the growth and popularity of JavaScript-based frameworks, such as React and Angular, front-end technologies can also be used to create functionality that was once reserved for back end languages.

These languages are also categorized as client-side languages because the browser is also referred to as the client. The client in this context is not someone you’re doing work for!

Back-end

Back-end developers are responsible for the “behind the scenes” functionality such as submitting payment information when making an online purchase or when you’re logging into an account.

Back end developers work with languages that run on a server, such as Python, PHP, C#, Ruby or Java. Back-end developers also work with database technologies, such as MySQL or MongoDB. You don’t need to know all of these languages to be a backend developer and many specialize in a couple of languages and may have some familiarity with others.

Full-stack

There’s also a third category, full-stack, which usually refers to someone who works with both front-end and back-end languages. While the exact languages a full-stack developer specializes in will vary, most are able to work with the foundational front-end languages (HTML, CSS, JavaScript), and one or two back-end languages. They may also have knowledge of JavaScript frameworks.

What skills should I focus on?

When starting out, trying to figure out what to learn can be confusing. If you’re more interested in the visual side of development, focus on gaining front-end skills. If you prefer the logic of building functionality, then focus on back-end skills. Or learn a bit of both to see if maybe full-stack is the best path for you.

My recommendation is to always start with the foundational languages. Frameworks and tools will come and go. But learning the essentials first will make it easier to build upon.

HTML Overview

HTML stands for HyperText Markup Language. Hypertext refers to the links that connect web pages to one another. Markup is how HTML is written, the structure and format used to display content in a web browser.

HTML Syntax

When learning any language, start by getting familiar with the grammar rules and building blocks of that language. When writing code, the syntax refers to these rules and patterns. When writing HTML markup, use HTML tags by wrapping each HTML element name within a left and right angled bracket.

<element>

An opening tag is used to mark the beginning of the element. A closing tag marks the end of the element and must always include a forward slash (/) before the element name. The content to be displayed in the browser is included between the tags.

HTML and CSS basics - element

HTML tags are often written inside of other tags. So when you’re nesting a tag, make sure to close the tags from inside out.

<p><strong>Just some example content.</strong></p>

Formatting HTML

Properly formatting your HTML markup is also important for organization. For the browser, writing all the tags on one line doesn’t matter.

<outertag><innertag>Some content</innertag><innertag>Some content</innertag></outertag>

But for us, it’s convention to use whitespace and indention to make it easier to read. Each nested element is usually written on its own line and indented once, using one tab key space. This will make it easier to see which tags are nested and where the tags open and close.

<outertag>
  <innertag>Some content</innertag>
  <innertag>Some content</innertag>
</outertag>

But there are also times where nested tags are written within the same line; when an inline element is nested within another inline element or a block element.

<h1>This is a block element.</h1>
<p>This is a block element containing an <strong>inline element</strong>.</p>
<div>
  <p>A block element nested within another block element.</p>
</div>

What does that mean? Well, in short, every HTML element is categorized as either an inline or block-level element.

When inline elements are shown in the browser, they are displayed on the same line. So when formatting the HTML, nested inline elements are usually included in the same line as well — in line. When block-level elements are displayed in the browser, they always start on a new line. So when formatting the HTML, block elements are usually written on their own line and indented when they are nested.

As your code gets more detailed, formatting will help you stay organized and make your code easier to read.

HTML Elements

There are many different types of HTML elements. Some are used to display different types of text-based content such as paragraphs (p), headings (h1, h2) and lists (ul, ol, li).

<!-- Text based elements -->
<h1>Main heading</h1>
<p>This is a paragraph.</p>
<ul>
  <li>list item</li>
  <li>list item</li>
</ul>

Other types of elements are used to create the page structure and to organize the content into related groupings such as the div, header or footer elements.

<!-- Contains structural elements to group & organize content -->
<div class="content-wrap">
  <header>
    <h1>Main heading</h1>
    <p>This is an introductory paragraph.</p>
  </header>
  <footer>
    <p>Contains final information related to the page such as:</p>
    <ul>
      <li>copyright info</li>
      <li>contact info</li>
      <li>and more!</li>
    </ul>
  </footer>
</div>

Void Elements

Another type of HTML elements are void elements, which do not define structure or content; they are the content. HTML tags are usually written in pairs but void elements are written using only an opening tag.

Here is an example of a paragraph tag, which is not a void element, and a br tag, which is a void element. (This element is used to create a line break within a block of text.)

<p>paragraph</p><!-- not a void element -->
<br> <!-- void element -->

In the older versions of HTML, a forward slash was also included after the tag name, which is why void elements are sometimes referred to as self-closing tags or elements.

<br> <!-- current version of HTML -->
<br /> <!-- previous version of HTML -->

The latest version of HTML does not require this, but you may still see the old syntax being used. Both formats are valid but I would recommend using the most current syntax.

HTML Semantics

These different HTML elements were created for web browsers to interpret the meaning of the content, referred to as semantics. Most HTML elements have semantic meanings but there are a few that don’t.

For example, the header element is used to group introductory page content such as an h1 tag, which is used to define the main heading on the page. But the div and span elements do not have any specific meanings and are usually used to group or wrap content for CSS styling purposes only.

<div class="content-wrap">
  <header>
    <h1>Main heading</h1>
    <p>This is an introductory paragraph.</p>
  </header>
  <footer>
    <p>Contains final content related to the page.</p>
  </footer>
</div>

Writing semantic HTML is basically you communicating with the browser.

HTML Attributes

Sometimes you’ll need to add some extra information to an HTML element. You can do so by adding an attribute. For example, the href attribute is used to add a URL to a link tag (a). Adding this information will actually take you to another web page or website when you select the link. Without it, the link will go nowhere.

<a href="<https://christinatruong.com>">My Website!</a>
<a>Link goes nowhere without the "href" attribute</a>

Attributes can also be used to change the behaviour of an element. For example, to make a form field a required field, add a required attribute to the element. The user will not be able to submit the form until they fill out all the required inputs.

<element attribute></element>
<element attribute="value"></element>
<element attribute='value'></element>

When using multiple attributes, order doesn’t matter but each attribute should be separated by a space. In the following example, the tag includes a src attribute, used to link to the image file, and an alt attribute, used to describe the image.

<img src="image.png" alt="description of image">

HTML Comments

HTML comments can be used to leave notes for yourself or for others, which can be useful when working on a team or on an open source project. Comments are also often used for hiding code for later use, for debugging and to organize the document.

To write a comment, start with a left angled bracket, followed by an exclamation mark and two dashes. Then close the comment with two more dashes and the right angled bracket. Any characters can be included as a comment as long as it remains within the opening and closing syntax.

<!-- Comments are included here. -->
<!-- ****** Another comment with text and symbols. ***** -->
<!--
  Here's a multi-line comment.
  I can write anything here as
  long as I close the comment.
-->

By following this syntax, the comment will only be seen in the source code and will not be displayed in the browser.

There’s a lot more to learn about HTML and I hope to focus more on specific concepts throughout this series but that pretty much sums up the general HTML concepts and common terminology.

CSS Overview

CSS stands for Cascading Style Sheet and was created to separate content from presentation. HTML elements are used to define the meaning of the content to the browser. CSS is used to determine how the elements will look by defining the colours, size, positioning of the element, and much more.

CSS Ruleset Syntax and Terminology

Styles are defined using a CSS ruleset, which is made up of various components.

selector {
  property: value;
}
  • Selectors are used to select the HTML elements to apply the styles to.
  • A declaration block is everything within and including the curly braces {} and is used to group together all the declarations for that selector.
  • A declaration is the actual style rule, which is written using a property and value, separated by a colon (:). Each declaration must also end with a semi-colon (;) to indicate that the instruction is complete.
  • A CSS property defines which style is applied to the element.
  • Values are specific to and define the characteristics of that property.

So in the following example, body is the selector, width is the property, and 100% is the value.

body {
  width: 100%;
}

Shorthand and longhand syntax

Many, but not all, CSS property values can be defined using a longhand or shorthand syntax.

When using shorthand, multiple longhand properties can be set using just one corresponding property. This is generally more efficient because you’ll end up writing less CSS overall. And it’s best to write just what you need.

/* shorthand */
padding: 20px;

/* longhand */
padding-top: 20px;
padding-right: 20px;
padding-bottom: 20px;
padding-left: 20px;

But! There are always exceptions to the rule and sometimes using the longhand syntax is the better choice, especially when you want to define a more specific style.

For example, just using the padding property with at value of 20px will apply this style to all four sides of the element. This is more efficient than using the longhand syntax, which would require four declarations. But if you only wanted to add some padding to the top of the element, then using the one longhand property, padding-top, would also be appropriate.

CSS basics padding

CSS Comments

Comments can also be written in CSS. And just like HTML comments, it’s used to help us read our code better. Start with a slash and asterisk (/*) and close the comment in the opposite order (*/). Any characters can be included as a comment as long as it remains within the opening and closing syntax.

/* This is a comment on one line */

/* 
   This is a comment
   over two lines.
*/

/* --------------------------------------
This is a comment using dashes to create 
visual separation. It is often used for 
organizing code in the CSS file.
-----------------------------------------*/

Use it to leave notes, or for organizing your code blocks, or to hide a line or block of CSS. This technique is used for debugging and testing by temporarily hiding different declarations from the browser, without actually deleting the code. To uncomment the code, delete the slash and asterisk surrounding the declarations.

header {
  /* height: 200px; */ 
  width: 400px;
}

/* 
h1 {
  font-size: 16px;
  color: red;
}
*/

Formatting and whitespace

Just like HTML, whitespace, line breaks and indentation are used to format CSS for readability. A common formatting convention is to write each declaration on its own line and indented with one tab key space, to make the groupings easier to see.

body {
  background: lightblue;
  font-size: 12px;
}
h1 {
  color: blue;
  font-size: 25px;
  font-weight: normal;
}

A white space between the property and value is not required but can also be added for readability.

/* both are valid */
padding:20px 10px;
padding: 20px 10px;

Often, when white space is required in a value, it’s used to separate multiple values used with a single property.

/* both are valid */
padding:20px 10px;
padding: 20px 10px;

/* both are not valid */
padding: 20px10px;
padding:20px10px;

After gaining some experience writing CSS, you’ll probably start to notice that everybody has a personal preference for how they format their code. You’ll likely develop your own style too. Just try to be consistent and use an organizational style that makes sense to you. I’ve included some extra resources at the end of the post.

And that pretty much wraps up this HTML and CSS overview! I’ll be posting videos and these companion pieces regularly about specific HTML elements or CSS properties, where I’ll dive a little deeper into each one, so subscribe to my YouTube channel to get notifications. And if you’re interested in doing a full course, I recommend my CSS Essential Training course on LinkedIn Learning.

 

How to Add a CSS Gradient Overlay to a Background Image

This article was originally posted at https://medium.com/@christinatruong/how-to-add-a-css-gradient-overlay-to-a-background-image-170216435f65 and was kindly shared by Christina Truong. Check out more of her work at https://christinatruong.com.

Using images on a web page helps to add visual interest. But figuring out how to place text on top of the image, while making sure you can still read it, can be challenging. There are a few different ways to get around this issue.

UNLIMITED DOWNLOADS: 400,000+ Fonts & Design Assets

Starting at only $16.50 per month!



 

Prefer to watch a video? This article is a companion piece to my Decoded by Christina series on YouTube.

Option 1: Choose the right background image

The easiest option is to use images that have a big blank area for your text or doesn’t have a lot of detail.

Choose the right background image

If you don’t have your own photos, there are plenty of free and paid options for stock photography such as Adobe Stock or Unsplash.

Option 2: Edit the background image

Maybe there’s a specific photo that you want to use but it doesn’t have any blank areas for text or has a lot of detail. Another option is to use Photoshop or other image editing software to change the overall color profile of the image. This can help light colored text stand out by darkening the background image or vice versa.

To create this effect, add a black or white background color on a layer underneath the image, and then change the opacity of the image, to darken or lighten the photo.

edit the background image

Example of editing images in Photoshop by changing the opacity and adding a background layer

You could also add a color overlay or de-saturate the photo to make it black and white. Depending on the image, these techniques can help to make the text stand out.

Example of editing images in Photoshop by adding a color overlay and de-saturating the image

Example of editing images in Photoshop by adding a color overlay and de-saturating the image

This might be okay if you have a few images but if you’re using a lot of photos, it might get cumbersome to manually edit all the photos.

Accessibility

If you are making edits to images, it’s best to avoid adding text to the image itself. For the visually impaired, screen readers are used to read out the text in an HTML document. If the text is in the image, then it can’t be read aloud. And you want your web pages to be as accessible as possible.

While you can and should add an alt attribute to your images, this attribute is used for describing the image itself.

<img src="image.jpg" alt="description of image"/>

And most of the time, when working with text and images, the image file is added as a background image using the CSS background or background-image property, so you won’t even be able to add an alt attribute. So just avoid doing it altogether!

body {
  /* shorthand */
  background: url(image.jpg) no-repeat;
  /* longhand */
  background-image: url(image.jpg);
  background-repeat: no-repeat;
}

Option 3: Use CSS!

Luckily, there are ways to work with text and background images using different CSS properties and techniques.

The color and text-shadow property

Sometimes just adjusting the text color, with the color property, will do the trick. If the image is mostly dark, use white or a light color to add contrast, or vice versa if the image is mostly lighter colors.

In the example below, the heading is in an area of the image that has less detail, so a color change kind of works. But the paragraph text is still hard to read since it’s in a more detailed area of the image.

Screenshot from the Codepen containing the full HTML and CSS example

Screenshot from the Codepen containing the full HTML and CSS example

Another option is to add a drop shadow, using the text-shadow property.

h1, p {
  color: white;
  text-shadow: 1px 1px 3px #444;
}
Screenshot from the Codepen containing the full HTML and CSS example

Screenshot from the Codepen containing the full HTML and CSS example

But I find this doesn’t always work well with more detailed images. Plus it can be tricky to add a drop shadow to longer blocks of text or smaller font sizes.

To learn more about how to add a drop shadow to text, check out my text-shadow post.

The background property

Another option is to use the background property, which allows for a couple different ways to add color to either the the text or the image. The background property is actually shorthand for many different properties but this post will focus on background-color and background-image.

background-color

Let’s start with taking a look at how to use background-color to add a color to the element, which will display underneath the text. This property can be used with any type of <color> value.

background-color can be added to a single element, such as the h1 tag, in the Codepen example. It can also be added to a group of elements by selecting the containing element, such as the text-container div, which will add a color to the container being used to group all the paragraphs.

h1 {
  background-color: white;
}
.text-container {
  background-color: white;
}
another Codepen screenshot with text over background image

Screenshot from the Codepen containing the full HTML and CSS example

To have more of the background image showing through, add transparency by using an rgba() colour value instead of a keyword or hex code.

/* sets the color with alpha transparency */
background-color: rgba(70, 130, 180, 0.8);

The first three values specify the red, green and blue components, using numbers between 0 and 255, with each value separated by a comma. 0 represents black and 255 represents white. All other colors are a combination of the remaining numbers. The last value sets alpha channel, which is how the transparency is added. Any value between 0 and 1 can be used. 0 is fully transparent and 1 is solid. A percentage value can also be used. For example 0.8 is the same as 80%.

Another Codepen screenshot showing text over background image

Screenshot from the Codepen containing the full HTML and CSS example

You can find RGB values using image editing software like Photoshop or other online resources. Here are a couple that I like to use:

  • colours.neilorangepeel.com — browse through a bunch of different colors and find the RGB, keyword or hex values
  • rgb.to — if you already have a color value and just need to convert it to RGB, this tool will do that

This technique will only add a background color to the elements, not the entire background image. Also, text-based elements are usually block-level elements, so they span the full width of their container. Adding a background-color to it will add the color all the way across the container, even if the text doesn’t span all the way across—as you can see with the “heading” in the above example.

If you don’t want that effect, there are some workarounds using the display value. View the video example for more details.

background-image to create a color overlay

To change the look of the entire background image itself, use the background-image property to add a color overlay to the whole image instead. Here’s how it works:

  • Multiple images can be displayed using the background-image property
  • A gradient can also be displayed using the background-image property
  • Use a gradient and a background image to display a color overlay on top of the image

The Syntax

Multiple background images are separated with a comma. The images will be displayed stacked on top of each other. The first image listed will be on top of the following image.

background-image: url(image1.png); /* one image */
background-image: url(image1.png), url(image2.png); /* two images */

Gradient CSS data types are used to display a transition between two or more colors. Here’s the syntax using the linear-gradient function and an image. Make sure to define the gradient value first to create the color overlay effect, since the first value displays on top.

background-image: linear-gradient(color, color), url(image.png);

Here’s how this technique looks using a gradient on top of a background image:

background-image: linear-gradient(rgba(0,0,0 0.2),rgba(0,0,0,0.8)),
                  url(<https://picsum.photos/id/1031/500/400>);

I’ve added a black overlay, using the rgba() color value to add transparency, to be able to see the background image underneath. A gradient function also requires at least two color values: the first value is the top of the gradient, the second value is the bottom of the gradient. Also, because the values for this style can be kind of long, I like to put the two different values on its own line, just to make it easier to read. This is just my personal preference for formatting this type of declaration.

If you don’t want a gradient effect, then use the same values for both the top and bottom of the gradient. If you want to keep the gradient effect, just change the opacity levels or choose different colors.

Because the rgba() value requires parenthesis, which is contained within the linear-gradient() function which also uses parenthesis, it easy to accidentally to either be short a bracket or have too many. So just be sure to double check your syntax.

See the Pen
Working with text and background images
by Christina Truong (@christinatruong)
on CodePen.light

Now you can tweak and edit as you please without the need to make any changes to the image file itself. To see a more detail breakdown of the techniques mentioned in the article, check out the corresponding video.

 

The text-shadow CSS Property

This article was originally posted at https://medium.com/@christinatruong/the-text-shadow-css-property-d1064bb1b27d and was kindly shared by Christina Truong. Check out more of her work at https://christinatruong.com.

When adding CSS styles to text on an HTML page, it’s usually best to keep it subtle, to make sure that the content on your page is easy to read. But sometimes you may want to make a small block of text stand out a little more than the rest. In this post, I’ll go over how to use the text-shadow CSS property to add a drop shadow to your text.

UNLIMITED DOWNLOADS: 500,000+ WordPress & Design Assets

Sign up for Envato Elements and get unlimited downloads starting at only $16.50 per month!



 

Prefer to watch a video? This article is a companion piece to my Decoded by Christina series on YouTube.

There are some basic ways to make your text stand out. You can make it bold, change the color, or use different font-sizes.

Another option is to use the text-shadow property to add a drop shadow. There are four values used with this property. Two are required, the offset-x and offset-y, and two are optional, the blur-radius and color value.

/* offset-x | offset-y | blur-radius | color */
text-shadow: 2px 2px 4px green;

Let’s go over how to define each value.

offset-x and offset-y

The offset-x value determines how far away, from the element, the shadow will appear on the x-axis, which runs left to right. The second value, the offset-y, determines the distance of the shadow on the y-axis, which runs top to bottom.

text-shadow

These values can be defined with any length data type, which is a number followed by any unit used to represent a distance value (e.g. px, em, rem or a percentage). Also, when using a property with multiple values, each has to be separated by a space.

/* offset-x | offset-y */
text-shadow: 2px 2px;

Since both the offset-x and offset-y values are required, if you add only value, you won’t see any change. But if you only want a shadow on the x-axis, then set the offset-y value to 0 or vice versa.

text-shadow: 2px 0px; /* will only show the shadow on the x-axis */
text-shadow: 0px 2px; /* will only show the shadow on the y-axis */

I used to always get the direction of the x- and y-axis mixed up until I saw an example using Beyoncé’s “Irreplaceable” lyrics as a reminder. In the song, she sings to her ex, “to the left to the left, everything you own in the box to the left.” So, ex (or x) to the left!

blur-radius and color

If you only define the offset-x and offset-y values, the shadow will look exactly like a copy of the text.

To create a softer shadow effect, add a third value, the blur-radius. This will blur the edges of the shadow. Any length data type can be used here as well. The larger the value, the bigger and more transparent the blur effect.

The last value is used to change the shadow from the default black colour to any other colour by adding a color value (e.g. keyword, hex code).

CSS text-shadow

Putting it all together

Most of the time, text-shadow effects are used add a subtle drop shadow and not quite like the example below. But for demonstration and testing, using values that create a more prominent style will make it easier to see what each value does.

See the Pen
text-shadow example
by Christina Truong (@christinatruong)
on CodePen.light

To make a text-shadow effect a little more subtle, I generally use a dark gray color or something that matches to the background colour, rather than pure black. This will create a softer shadow. (Note that the hex values in the example is using the shorthand notation.)

For the other values, I find that 1–3px is usually enough to give you just a bit of a shadow effect without overwhelming the text. Though there are always exceptions to the rule so I would suggest playing around with different values to get the effect you’re looking for. But in a nutshell, this is how you add a drop shadow to your text.

And that’s it!