Tag: CSS

Create Dynamic Text on a Path with HTML, SVG, and CSS

When it comes to incorporating irregular shaped text into web projects, we often end up using images. However, there may be a better way – using inline SVG and CSS to create dynamic, responsive, and accessible graphics directly within our HTML. In this post, we’ll walk you through the process of achieving this, ensuring our designs are on point while maintaining accessibility and SEO friendliness.

The Power of Inline SVG

Have you ever encountered design elements that you thought could only be achieved with externally sourced images? Something like this for example:

Well, this may not be your only option. By leveraging inline SVG and some simple CSS, we can build captivating graphics right within our HTML documents. In this post I’ll show you exactly how to do this.

Working with SVG

To begin you’ll need to start with a vector graphic of your design. Also you’ll need to be able to edit it yourself in a vector graphics editor like Adobe Illustrator, or you’ll need to have someone who can help you do so. This is because we need to edit our images to add an invisible path for our text to be placed on. In my case, these were my original graphics:

I opened them up in illustrator and added a path to each of them for the text to sit on. I placed the path for the first banner banner here.

For the purposes of this demo I added a black stroke to it just so that you can see where the path is placed but in the end it will be invisible. As you can see, I made the path span the entire width of the main region of my banner so that the text can expand all along this path accommodating phrases of varying lengths.

For the second banner I did the same. Here’s where I placed the text path:

After your invisible text paths have been added, you’ll just need to export the banners as SVG. At this point, it’s probably a good idea to optimize these SVG while you’re at it. I like to use Jake Archibald’s SVGOMG tool when doing this type of thing.

Creating the Inline SVG Banner

Now that you have your optimized SVG graphic with the invisible text path, let’s integrate it into your HTML. You’ll want to and paste it directly into our document:

HTML
<!DOCTYPE html>
<html>
  <body>
    <svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 691.3 201.8">
      <g id="banner">
        <path d="M148.6 79.6V21.7c-6.6-3.1-13.7-5.6-20.7-7.7C86.6 1.7 42.7-1.8 0 3.7c25.3 17.2 47.2 39.5 64.1 65.1-20.7 9.5-39.2 23.8-53.6 41.4C52 112.3 93 123.8 129.3 144l19.3-64.4zM549.7 121.8v57.9c45 16.4 94 22 141.6 16.2-27.4-15.1-50.8-37.4-67.1-64 13.4-3.9 26.3-9.4 38-16.9 10.6-6.7 20.2-15.1 28-24.8-39-3.5-77.1-15.7-114.3-28.4l-26.2 60z" class="st0"/>
        <path d="M105 46c0-13.7 11.2-24.8 24.9-24.6l18.7.3v46.5c-13.5-4.8-26.5-11.1-38.5-18.8L105 46zM549.7 179.7v-39.9c14.8 5.8 28.9 13.3 41.7 22.6 0 9.6-7.8 17.4-17.4 17.4h-24.3z" class="st1"/>
        <path d="M591.3 160.8v1.6c-26.5-19.1-58.4-31-90.9-35.1-45.1-5.7-91.4 3-133.2 20.8-35.8 15.2-69 37-106.5 47.3-52.4 14.5-111 4-155.7-26.8V46.1C149.7 77 208.2 87.4 260.7 73c37.5-10.3 70.7-32.1 106.5-47.3C409.1 7.8 455.3-.9 500.4 4.8c32.5 4.1 64.4 16 90.9 35.1v120.9z" style="fill:#3dc0d1"/>
      </g>
      <path id="text-path" d="M108.7 124.1c44.2 29 101 38.4 152 24.4 37.5-10.3 70.7-32.1 106.5-47.3 41.9-17.8 88.1-26.4 133.2-20.8 31.7 4 62.7 15.3 88.7 33.6"/>
    </svg>
  </body>
</html>

Now we can add the text using a text node. And, Since we’re placing the text on a path, we’ll use a textPath element within our text node:

HTML
<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 691.3 201.8">
  ...
  <path id="text-path" d="M108.7 124.1c44.2 29 101 38.4 152 24.4 37.5-10.3 70.7-32.1 106.5-47.3 41.9-17.8 88.1-26.4 133.2-20.8 31.7 4 62.7 15.3 88.7 33.6"/>
  <text>
    <textPath>Welcome Everyone!</textPath>
  </text>
</svg>

To link the text to the path in our graphic we add an href to our textPath referencing the id of the invisible path for our text:

HTML
<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 691.3 201.8">
  ...
  <path id="text-path" d="M108.7 124.1c44.2 29 101 38.4 152 24.4 37.5-10.3 70.7-32.1 106.5-47.3 41.9-17.8 88.1-26.4 133.2-20.8 31.7 4 62.7 15.3 88.7 33.6"/>
  <text>
    <text>
      <textPath href="#text-path">Welcome Everyone!</textPath>
    </text>
  </text>
</svg>

Now our text should appear on our path but it won’t be aligned properly. To center the text, we will need to give our path a length that is divisible by two, in our case let’s just make it two. And we’ll add a startOffset of one to our textPath element which will now make it start in the center of the path:

HTML
<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 691.3 201.8">
  ...
  <path id="text-path" pathLength="2" d="M108.7 124.1c44.2 29 101 38.4 152 24.4 37.5-10.3 70.7-32.1 106.5-47.3 41.9-17.8 88.1-26.4 133.2-20.8 31.7 4 62.7 15.3 88.7 33.6"/>
  <text>
    <text>
      <textPath href="#text-path" startOffset="1">Welcome Everyone!</textPath>
    </text>
  </text>
</svg>

At this point it still isn’t quite centered. So we can add a text-anchor style to properly align this.

CSS
textPath {
  text-anchor: middle;
}

There we go, now our text is properly centered. The final styles I added to my text are:

CSS
textPath {
  fill: #024949;
  font-size: 225%;
  font-weight: 700;
  letter-spacing: 0.02em;
  text-anchor: middle;
  text-shadow: 0 1px 0 rgba(255, 255, 255, 0.8);
}

And, when we resize our viewport we can see that everything scales great. And what’s great about this is that the text can be changed by simply editing the HTML. Of course, if we add too much text it will break at some point but it does have some flexibility. This method is not only visually appealing but also accessible and SEO-friendly, as the text is embedded in the document like any other text.

Conclusion

Using inline SVG and CSS, you can achieve some pretty neat stuff directly within your HTML without the need for images. The combination of accessibility, responsiveness, and SEO-friendliness makes this approach a valuable addition to your web design toolkit. Whether you’re displaying messages, promotions, or information, this method offers a creative way to enhance your website’s visual appeal in certain circumstances.

Want to See It in Action?

Check out the demo code and examples of this technique in the in the codepen example. If you have any questions or thoughts, don’t hesitate to leave a comment.

Styling HTML Radio Buttons: A Step-by-Step Guide

HTML radio buttons are a staple of web forms, but their default appearance leaves much to be desired. In this blog post, we’ll walk through one of my favorite methods to customize the look of radio buttons using CSS, creating a more user-friendly and visually appealing experience.

Let’s Begin by Hiding the Radio Buttons!

We need to start by acknowledging the limitations of cross-browser styling for radio buttons. While it’s frustrating that we can’t style them directly, we can use workarounds. In this example, the first step is to hide the actual radio button input. I know this sounds odd but we know that we can’t style them, so we just need to take them out of the equation. However, this should be done in an accessible manner, ensuring that it remains functional for all users. This can be achieved by using the following set of styles that visually hide the content while retaining its usability:

CSS
input[type="radio"] {
  border: 0 !important;
  clip: rect(1px, 1px, 1px, 1px);
  height: 1px !important;
  overflow: hidden;
  padding: 0 !important;
  position: absolute !important;
  width: 1px !important;
}

Creating the Custom Radio Buttons

To create the custom appearance of the radio button, we’ll leverage the ::before pseudo-element on our label along with some simple CSS to create the look we’re looking for.

For our example, the HTML looks like this:

HTML
<form>
    <h1>Can We Style HTML Radio Buttons?</h1>
    <ul>
        <li>
            <input type="radio" value="yes" name="option" id="yes" />
            <label for="yes">Yes</label>
        </li>
        <li>
            <input type="radio" value="no" name="option" id="no" />
            <label for="no">No</label>
        </li>
        <li>
            <input type="radio" value="maybe" name="option" id="maybe" />
            <label for="maybe">Maybe</label>
        </li>
      </ul>
</form>

To start, we’ll add the following styles to our label element:

CSS
label {
  display: inline-flex;
  align-items: center;
}

This will ensure that once we add our radio button styles it will be properly vertically aligned with the label text.

Now, we’ll add our mock radio buttons using the ::before pseudo-element:

CSS
label::before {
  content: '';
  display: block;
  height: 1.25em;
  width: 1.25em;
  border: solid 1px #ccc;
  border-radius: 50%;
  margin-right: 0.5em;
}

At this point we have something that is starting to resemble a radio button list but if we click on the radios, we will see that nothing is happening. Although the pseudo-element visually resembles a radio button, it lacks interactivity because we have not yet handled the checked state.

Handling Interaction and States

We can handle the checked state with the :checked pseudo-class and adjacent sibling selector on our label:

CSS
input[type="radio"]:checked + label {
  color: black;
}

For the inner dot we can leverage a radial gradient on our pseudo-element:

CSS
input[type="radio"]:checked + label::before {
  background: radial-gradient(0.75em circle at center, currentColor 50%, transparent 55%);
  box-shadow: 0 0 1em 0 rgba(10, 150, 255, 0.75);
  border-color: currentColor;
}

There, now when we click on these they function much like native radio buttons. And we can enhance the interactions by adding some transition effects:

CSS
label::before {
  ...
  transition: border ease-in 150ms, box-shadow ease-in 150ms;
}

Let’s not Forget About Focus

To improve accessibility, we will also need address the focused state of the mock radio buttons. This time we will need to utilize the :focus pseudo-class and the adjacent sibling selector with the label:

CSS
input[type="radio"]:checked + label,
input[type="radio"]:focus + label {
  color: black;
}

input[type="radio"]:focus + label::before {
  box-shadow: 0 0 1em 0 rgba(10, 150, 255, 0.75);
  border-color: currentColor;
}

Conclusion

By following this method, we can create stylish and accessible custom radio buttons that greatly enhance the user experience. These customized radio buttons not only look better than the standard ones but can also provide better feedback and interaction when implemented properly.

This was a pretty simple example that may not even really look much different than the native browser styles but the key is, with this set up we can pretty much do whatever we want. So, feel free to experiment with the styles and adapt them to your project’s design.

Want to See It in Action?

Check out the demo code and examples of this technique in the in the codepen example. If you have any questions or thoughts, don’t hesitate to leave a comment.

Remember that with a little creativity and some CSS, you can transform the appearance of HTML radio buttons to match your design while maintaining accessibility and usability!

CSS Shapes Bring Rich Editorial Design Features to the Web

For the longest time we’ve been stuck with boxes and it makes things that are common yet beautiful in the print world difficult if not impossible on the web. CSS shapes change this, leveling the playing field allowing us to create much more engaging layouts and designs on the web.

Layout on the web is undergoing a major transformation. Things like Flexbox, CSS Grid, and now CSS Shapes are really helping to modernize layout on the web and browser vendors are listening by adding support for these features.

In my newest Pluralsight course, Thinking Outside the Box with CSS Shapes, we cover how web designers/developers can use CSS shapes to create rich, complex layouts like those common in print design. This course will introduce you to the CSS Shapes specification and show you how to use its properties in-depth. You’ll learn about various interesting use cases and examples, ranging from basic to complex, as well as the future of the spec, browser support, and helpful tools and resources. By the end of this course, you’ll be up and running with CSS shapes, and thinking about web design and layout in a whole new way.

Fixing the :active Pseudo Class Selector in Internet Explorer

Sometimes it’s necessary to have a link that contains some children elements. Say, for example, you have a link that contains some text and an inline SVG icon that’s styled using CSS. This set up allows you to style the icon for all of the link states :hover, :visited, and :active right? Well yes, with the exception of the :active state in Internet Explorer. Well, not without a work around at least.

How it Should Work

Say I want apply a transform: scale(0.7); to an inline svg when the link is active.

The HTML

<a href="/info.html">
    <svg viewBox="2.672 2.672 26.656 26.656">
        <path d="M16,2.672C8.639,2.672,2.672,8.64,2.672,16c0,7.361,5.968,13.328,13.328,13.328c7.359,0,13.328-5.967,13.328-13.328 C29.328,8.639,23.359,2.672,16,2.672z M16,28.262C9.239,28.262,3.738,22.761,3.738,16S9.238,3.738,16,3.738 c6.762,0,12.262,5.501,12.262,12.262S22.762,28.262,16,28.262z"/>
        <path d="M14.974,9.978c0-0.286,0.087-0.528,0.262-0.726c0.175-0.196,0.435-0.295,0.778-0.295c0.344,0,0.604,0.099,0.784,0.295 c0.178,0.197,0.266,0.439,0.266,0.726s-0.088,0.525-0.266,0.716c-0.18,0.191-0.439,0.286-0.784,0.286 c-0.343,0-0.603-0.095-0.778-0.286C15.062,10.503,14.974,10.264,14.974,9.978z M16.884,23.043h-1.767V12.717h1.767V23.043z"/>
    </svg>
    Click Me!
</a>

The CSS

a:active svg {
    transform: scale(0.7);
    transition: transform 0.1s ease;
}

The Result

The Problem: This Doesn’t Work in IE

If you try the example above in Internet Explorer the transform will not be applied, even in ie11. Well, actually it will be applied if you click on the link anywhere that is not the inline SVG. If you click the text for example you will see the transition occur.

The Fix

To fix this I can simply place a pseudo element :before or :after on the link above all of its contents. This will effectively set the clickable area of the link on a layer above its contents meaning that the click will occur on the link and not the SVG.

First, Set the Stacking Context

a {
    position: relative;
}

Then, Style the Pseudo Element

a:before {
    content: "";
    display: block;
    position: absolute;
    top: 0;
    right: 0;
    bottom: 0;
    left: 0;
}

The Result

Oh Wow That’s Neat – 20: Dimensions Toolkit

We are all designing and building responsive websites now. For many of us this means both exciting new challenges and significant increases to our workload. Testing at many variable widths is more and more difficult to do and is likely the culprit of much of our increase in development time.

We are all designing and building responsive websites now. For many of us this means both exciting new challenges and significant increases to our workload. Testing at many variable widths is more and more difficult to do and is likely the culprit of much of our increase in development time.

There are many great tools that have been created during this responsive web design movement. One of the best that I’ve seen so far is Dimensions Toolkit created by online marketing and design specialists Surge Digital.

Dimensions Toolkit

Dimensions Toolkit is really great. It allows you to pass it your url and then test your site at many different dimensions based on many common devices. It also allows you to create your own breakpoint tests and then it will remember these settings the next time you use it.

Another great feature is the ability to work offline. That’s right, if you’re using the Chrome extension, it will work when you’re not connected to the internet.

It even works with all those great JavaScript auto-refreshers like LiveReload so you won’t even have to hit refresh to see it work its magic.

More Info

You can get more info here

The Online Version

You can use the online version here

Buy the Chrome Extension

You can buy the Chrome extension for $1.99/year here

How to Force Hardware Acceleration to Improve CSS Animations

You’ve likely seen CSS animations and transitions in various web applications out there where they just didn’t work well. They are choppy and freeze along with a bunch of other issues. This occurs because they are not taking advantage of the device GPU and hardware acceleration, but are instead using the browsers’ built in rendering engine.

Well, with a few lines of CSS we can fix this. Modern mobile and desktop browsers will now trigger hardware acceleration to aid with performance of certain complex CSS calculations. 3D transformations are the best way to set this up.

All you have to do is add something like this

CSS
.accelarate {
   -webkit-transform: translateZ(0);
   -moz-transform: translateZ(0);
   -ms-transform: translateZ(0);
   -o-transform: translateZ(0);
   transform: translateZ(0);
}

As you can see from this code there are not actually any 3D transformations taking place since tranzlatez is set to 0 but the existence of this property will hand the rendering off to the GPU.

Considerations

As you can see this is somewhat of a hack so you should use it sparingly. It should only be used on items that are being animated due to the fact that over utilizing the GPU can cause performance issues itself as well as battery drain. Also, in order to get the biggest performance gains you should try to enable GPU acceleration on as few HTML elements as possible.


ie9 and above Chrome Fire Fox Safari

Hardware acceleration has good support working in all modern browsers


Sources

Oh Wow That’s Neat – 19: Responsive Boilerplate

With all of the great frameworks popping up it can be difficult to choose the “right” one. Besides doing some really great things, probably the two most popular frameworks Twitter Bootstrap and Zurb Foundation, can be a little overreaching at times when it comes to theming them. You may find that you have to overwrite and undo many styles to make them look unique. This is where web developer James South’s Responsive Boilerplate may prove to be that “right” one.

Responsive Boilerplate

Responsive has many of the elements that you know and love from other popular frameworks but the key difference is that they are given only the most basic styling. This means that you wont have to overwrite and undo as much and can more efficiently add your theme layer.

It is extremely light weight at only 20.6kb minified and gzipped. The goal is to keep it small and in return this will help keep your code small since you won’t really need to peel out the theme of the framework itself just to add your own look.

It is intended to be dropped into your sites similar to how you would a normalize.css file.

More Info & Download

You can get more info here and you can download it here

Alter Browser Default Panning and Zooming Behavior With CSS touch-action

Now that there are so many people accessing the sites we build through touch devices many of us will see that we need to alter the default panning and zooming behavior of the browser when touching them.

Drawing Example

The easiest example to help you understand this property is through a simple canvas drawing demo. Below you can see that if you drag your cursor over the box it will draw properly wherever your mouse pointer goes. However, if you drag your finger over the box on a touch device you will create a bunch on single dots or you will drag the entire page left, right, up, or down and no drawing will occur.

Drag your mouse over the box below:

If you are using a touch screen you can try it and see how it works differently.

CSS touch-action to the Rescue

In order to resolve this issue you can use the CSS touch-action property. It can control how touch actions, panning and zooming, are triggered on elements within the page. Simply adding the following code will prevent the default behavior in supporting browsers:

CSS
touch-action: none;

Drag your mouse or finger over the box below:

Regardless if you’re using your mouse or your finger on touch devices it should now work the same. **NOTE – if you are using anything other than ie10 or ie11 on your touch device the demo will not work.

CSS touch-action Values

The CSS touch-action property has a handful of different values that can be set.

  • auto — this is the default value and will leave the touch behaviors up to the browser
  • none — will not trigger any touch behaviors on the specified elements
  • pan-x — will allow content to horizontally scroll on the specified elements
  • pan-y — will allow content to vertically scroll on the specified elements
  • manipulation — will allow scrolling and zooming on the specified elements

Special Considerations

Just a couple of special considerations to keep in mind when using touch-action. The touch-action property is part of the pointer-events specification which is still in the candidate recommendation phase. This means that it is both subject to change and likely to gain support in all major browsers at some point.

It only applies to elements that support both the CSS width and height properties. This is in place to help with performance issues for low-latency touch actions. So if you are using it on inline items you will want to them to display: block in order to achieve anticipated behavior.


Browser Support

ie9 and above

The touch-action property doesn’t have very good browser support only working in internet explorer 10+ and you need to use the “-ms-” prefixed version in ie10. For Chrome, support is supposedly just around the corner so keep an eye out.


Sources

Oh Wow That’s Neat – 18: Morphing Buttons Concept

It used to be that websites and their interactions were much different than those from native software applications. Well this is not so much the case anymore. Mary Lou, a freelance web designer and developer from tympanus.net, wrote an interesting article discussing a few different morphing buttons concepts that showcase some amazing possibilities for web interactions.
Morphing Buttons Concept

She has created a handful of really nice interaction effects that occur when buttons are clicked. They appear as if content or elements are contained from within them and when clicked they transition out from within the button in many different ways.

They are great effects but you will want to keep in mind that they only work in more modern browsers.

More info

You can read the full article here

Demo & Download

You can see a demo here and you can download it here

Quick Tip – 17: How to Diff CSS Live Edits in Chrome DevTools

If you’re reading my blog I’ll assume that you are familiar with how to live edit code within all browser developer tools. I use them all the time and can hardly remember what it was like without them. Chrome DevTools tend to be my favorite but FireFox and Internet Explorer continue to improve.

Chrome DevTools have the best and most complete offering as well as some really great features. One nice feature that I recently learned about is the ability to diff your live edit CSS changes directly from within DevTools.

Here’s How You Do it

When inspecting styles, click the link to the external stylesheet to open it in the “Sources” tab

When inspecting styles, click the link to the external stylesheet to open it in the Sources tab

Edit & Save Styles

Edit some styles and then save them (ctrl + s)

Edit some styles and then save them

Navigate to “Sources”, “Local”

Right click within the “Sources” tab content area and select “Local Modifications”

Right click within the Sources tab content area and select Local Modifications

History Panel

This will open the history panel where you can diff your edits

This will open the history panel where you can diff your edits

Oh Wow That’s Neat – 17: Open Source Ampersands

Paul Irish created and maintains a site devoted to Ampersands. The site is a collection of open source web fonts that only contain the ampersand character. He created it based off an article from 2008 regarding the usage of ampersands and the fact that certain variants of the character in some fonts are more interesting than others. The article also points out that the ampersand character is often used only for display purposes and not in content so there is no reason not to use more interesting versions.

Open Source Ampersands

With Open Source Ampersands you can view all of the fonts available, choose one that you like, download it including 4 font formats and a demo.html file demonstrating how to use it. All of the fonts are 100% open source from the Google Web Fonts Directory, The League of Moveable Type, and Kernest.

More Info

You can get more info about Open Source Ampersands and how to use it here.

CSS Pseudo Classes for Form Elements

CSS provides us with a handful of pseudo classes that are specific to HTML5 forms. They allow us to create forms that are easier to fill out by highlighting fields that are required, optional, valid, invalid, etc.

Pseudo Classes for Forms

The following pseudo classes are all related to form elements with examples on how they are used.

:default

The :default pseudo class applies to the default element in a group of similar elements within a given form. For example, if you have a form that has a submit and cancel button you could select the default button using :default.

See the Pen gsilz by Brian (@brianmtreese) on CodePen.

:default is supported in

Chrome 10 and aboveFire Fox 4 and aboveOpera 10 and aboveSafari 5 and above

:required

The :required pseudo class applies to any input with the required attribute set within a given form. This can be very useful to highlight the required fields within a form.

See the Pen dynGK by Brian (@brianmtreese) on CodePen.

:required is supported in

ie10 and aboveChrome 10 and aboveFire Fox 4 and aboveOpera 10 and aboveSafari 5 and above

:optional

The :optional pseudo class applies to any input without the required attribute set within a given form. May or may not be useful since most of the time simply highlighting the required fields will be enough.

See the Pen vCgpo by Brian (@brianmtreese) on CodePen.

:optional is supported in

ie10 and aboveChrome 10 and aboveFire Fox 4 and aboveOpera 10 and aboveSafari 5 and above

:valid

The :valid pseudo class applies to any input that contains valid data within a given form. This can be very useful as it will provide the user with feedback as they are filling out the form.

See the Pen JcFhe by Brian (@brianmtreese) on CodePen.

:valid is supported in

ie10 and aboveChrome 10 and aboveFire Fox 4 and aboveOpera 10 and aboveSafari 5 and above

:invalid

The :invalid pseudo class applies to any input that contains invalid data within a given form. This can be very useful as it will provide the user with feedback as they are filling out the form.

See the Pen ItkGn by Brian (@brianmtreese) on CodePen.

:invalid is supported in

ie10 and aboveChrome 10 and aboveFire Fox 4 and aboveOpera 10 and aboveSafari 5 and above

:in-range

The :in-range pseudo class applies to any form element that contains a value within the specified range for the input within a given form. Similar to valid/invalid it can be useful for providing feedback to the user when filling out the form.

See the Pen fckHB by Brian (@brianmtreese) on CodePen.

:in-range is supported in

Chrome 10 and aboveFire Fox 28 and aboveOpera 11 and aboveSafari 5.2 and above

:out-of-range

The :out-of-range pseudo class applies to any form element that contains a value outside the specified range for the input within a given form. Similar to valid/invalid it can be useful for providing feedback to the user when filling out the form.

See the Pen yirbF by Brian (@brianmtreese) on CodePen.

:out-of-range is supported in

Chrome 10 and aboveFire Fox 28 and aboveOpera 11 and aboveSafari 5.2 and above

:read-only

The :read-only pseudo class applies to any input with the readonly attribute set on it in a given form. It can be useful to gray out disabled fields for forms.

See the Pen BodAt by Brian (@brianmtreese) on CodePen.

:read-only is supported in

ChromeFire FoxSafari

:read-write

The :read-write pseudo class applies to any input without the readonly attribute set on it in a given form.

See the Pen GmAwz by Brian (@brianmtreese) on CodePen.

:read-write is supported in

ChromeFire FoxSafari


Client Side Only

The important thing to remember when using CSS and HTML validation to style your forms is that they are only client side validation. You will still need to validate on the server as well. The role that CSS and these pseudo classes play is to simply enhance the form and make it easier for users to fill out.


Sources

Oh Wow That’s Neat – 16: Brick. Webfonts that actually look good.

For those of you who have taken advantage of web fonts you’ve likely noticed various levels of quality. Sometimes, in some browsers, they look great. Other times, in other browsers, they look thin grainy. And if you’re like me you probably just cringed a little and dealt with it. Well, fortunately we now have help thanks to Alfred Xing who has created Brick.

Brick.im

Brick is a free, open source font library project. The difference between Brick and other web font providers is that it serves up the original font in WOFF format without compression. Other providers compress the heck out of their fonts. Brick doesn’t.

The fonts are served through Fastly’s CDN from their U.S. and Europe locations. Usage is easy and familiar working very similar to popular web font libraries like Google fonts. You can see complete details about usage here. There are quite a few fonts available for your use. You can see the entire list here.

While I have not personally used Brick in any sites I do like the ideas behind it. There is a small list of known sites that are using it and you can see them here.

More Info

You can get more info about Brick and how to use it here.


Browser Support

ie9 and aboveChrome 6 and aboveFire Fox 3.5 and aboveOpera 11.10 and above5.1 and above

The WOFF font format has pretty good browser support working in all modern browsers. Not supported in ie8 and below.

Using CSS Generated Content

Back in the good ol’ days, CSS was much more limited than it is today. If we needed to style something it had to be in the page which, in turn, led to bloated markup simply for design purposes. Luckily we are no longer in those days.

CSS Generated Content is one of many advancements in CSS that allows us to do more with less. It has been around for some time now and has good browser support so if you’re not using it you may want to consider it.

What is CSS Generated Content?

CSS Generated content is just content that is not actually in the markup and is not actually part of the DOM. It’s added using the CSS content property via the ::before and ::after pseudo elements providing two additional items for every element in the page that can be styled.

You Can Leave Them Empty

If you need to use the ::before and ::after pseudo elements for styling purposes only you can just add them and leave the content property empty.

CSS
p img {
    float: right;
}

p:after {
    border-top: solid 1px red;
    content: '';
    clear: both;
    display: block;
}

HTML
<p>
    <img src="https://briantree.se/wp-content/uploads/2014/02/62H-150x150.jpg" alt="Using CSS Generated Content to Clear Floats" width="150" height="150" />
    Lorem ipsum dolor sit amet, consectetuer adipiscing elit. Aenean commodo ligula eget dolor. Aenean 
    massa. Cum sociis natoque penatibus
</p>

Using CSS Generated Content to Clear FloatsLorem ipsum dolor sit amet, consectetuer adipiscing elit. Aenean commodo ligula eget dolor. Aenean massa. Cum sociis natoque penatibus dolor sit amet, consectetuer adipiscing elit. Aenean commodo ligula eget dolor. Aenean massa. Cum sociis natoque penatibus

You Can Use Static Text

If you want to add static text before or after elements you can simply set a text string value on the content property.

CSS
a:before {
    border: solid 1px red;
    content: '(.doc) ';
}

HTML
<a href="word-document.doc">A Word Document</a>

You Can Use Dynamic Attribute Values

If you have attributes on elements you can output their values before or after them.

CSS
a:after {
    border: solid 1px red;
    content: " ("attr(href)")";
}

HTML
<a href="https://briantree.se">My Website</a>

You Can Use CSS Counters

You can generate cool customized listings using CSS Counters. To learn even more about them you can check out my previous article “Make it Count with CSS Counters“.

CSS
.tableOfContents ol { 
    counter-reset: tcCount; 
    list-style: none; 
} 

.tableOfContents li:before { 
    border: solid 1px red;
    counter-increment: tcCount; 
    content: counters(tcCount, "."); 
    display: inline-block; 
    margin-right: 20px; 
    text-align: right; 
    width: 80px; } 

.tableOfContents > ol > li:before { 
    border: solid 1px red;
    content: "Part " counter(tcCount); 
} 

.tableOfContents > ol ol { 
    font-size: 75%; 
    margin-bottom: 20px; 
}

HTML
<ol>
    <li>
        This is the 1st Part
        <ol>
            <li>This is a section</li>
            <li>This is a section</li>
            <li>This is a section</li>
        </ol>
    </li>
    <li>
        This is the 2nd Part
        <ol>
            <li>This is a section</li>
            <li>This is a section</li>
            <li>This is a section</li>
        </ol>
    </li>
    <li>
        This is the 3rd Part
        <ol>
            <li>This is a section</li>
            <li>This is a section</li>
            <li>This is a section</li>
        </ol>
    </li>
</ol>
  1. This is the 1st Part
    1. This is a section
    2. This is a section
    3. This is a section
  2. This is the 2nd Part
    1. This is a section
    2. This is a section
    3. This is a section
  3. This is the 3rd Part
    1. This is a section
    2. This is a section
    3. This is a section

You Can Do More: CSS Generated Content Values

With the content property you can do more than what I’ve mentioned in this article. There are several values that can be used with the property.

none

When setting content to none the pseudo elements will not be generated

normal

This is the default value and equals a value of none for the pseudo elements

string

This creates static text content for the pseudo elements

uri

This links to an external resource like an image

counter

This specifies incremented counters for each item in the group of matched elements

attr

This displays the value of the attributes on the matched elements

open-quote | close-quote

This displays the proper open or close quote for the matched elements

no-open-quote | no-close-quote

This does not render any content but continues to increment the nesting of quotes


When Not To Use CSS Generated Content

The content property is powerful but just like everything else it can easily be used in ways that it shouldn’t be. As I mentioned above CSS Generated Content is not part of the DOM so it should not be used to add any content that would need to be accessible in the absence of CSS. This means that any sort of body copy, button text, form labels, or anything similar should not be added using the content property.


Browser Support

ie8 and above Chrome 31 and above Fire Fox 27 and above Safari 7 and above

CSS Generated Content has good browser support working in all modern browsers. Not supported in Internet Explorer 7 and below.


Sources

Quick Tip – 15: How to Fix ng-cloak Flicker in AngularJS

The ng-cloak directive was added to Angular in order to prevent the flickering of elements before your application has fully loaded. It then removes ng-cloak once it has had a chance to compile your views. However, there is still a flicker issue that occurs between when the view is first loaded and before Angular has had a chance to run.

How ng-cloak Works

The way that ng-cloak works is to add display: none !important to items using it. The following code comes directly from the angular.js source file:

CSS
[ng:cloak], 
[ng-cloak], 
[data-ng-cloak], 
[x-ng-cloak], 
.ng-cloak, 
.x-ng-cloak {
  display: none !important;
}

So, What’s the Problem?

The problem is that the style used to hide these items is included in the JavaScript file which takes a second to initialize. In this time period the CSS will not be parsed by the browser.

The Fix

It is only a brief flicker but it is still undesired. Fortunately the fix is a very simple one. All you need to do is add the above CSS somewhere in your application stylesheet. That’s all there is to it.

Oh Wow That’s Neat – 15: The Magic of CSS

We pick up lots of pieces of knowledge over time when working with CSS and then if we don’t use them often we can forget how to use them and then have to spend time either looking it up again or looking for where we used them in other projects.

Well, Adam Schwartz, a Principal Software Engineer at HubSpot has created a nice little resource documenting the stuff that he’s learned about CSS called The Magic of CSS.

The Magic of CSS

In his book he has captured some really great details, hints, tips and put it together in a really nice and easy to process manner. The topics covered range from basic to advanced but require an understanding of how CSS works.

Chapters

It looks like it will be a pretty good resource as he continues to update it and add new content.

More Info

You can get more info and read the book here

SVGs are So Fresh to Defs

No, this is not a hip hop song about SVGs, sorry to those of you who were expecting that. This is another post about good ol’ SVG graphics. So most of us know that there is a lot that you can do with SVGs and it can all be done in many different ways. The SVG defs element can be used to make SVG code simpler, cleaner, and better.

What Exactly is the Defs Element?

The SVG defs element is a used to contain items that can be referenced and reused from within the current SVG document.

Items contained within the defs element are not actually rendered because they are not part of the “rendering tree” but they are part of the “source tree” so they they are available and are able to be referenced elsewhere.

For performance reasons it is recommended that the defs element come before all other elements. Since it contains items that are referenced from other locations within the document it works better when they are created before they are referenced.

It is also recommended to use the defs element whenever possible because it’s easier to understand from a readability perspective and it’s also better for accessibility.

How is it Used?

Let’s say you have a design that makes use of multiple circles. You can just add one circle item in the defs element and then call it using the SVG use element like so:

HTML
<svg height="130px" width="250px">
    <defs>
        <circle id="circle" cx="50" cy="50" r="50" />
    </defs>
    <use xlink:href="#circle" x="10" y="20" fill="#00deb7" />
    <use xlink:href="#circle" x="130" y="20" fill="#ff495d" />
</svg>

One way that you could use this is if you were to save all of the icons for your website or application into a single SVG. You could then grab all of the reusable elements and toss them into your defs element and then just call them setting them up with CSS for those icons that use them. This could greatly simplify and reduce your overall code within the SVG file itself.

A Real World Example

See the Pen SVG Defs and Use by Brian (@brianmtreese) on CodePen.

Browser Support

ie9 and above Chrome 17 and above Fire Fox 17 and above Safari 6 and above

The SVG defs element has good browser support working in all modern browsers. Not supported in Internet Explorer 8 and below.


Sources

Oh Wow That’s Neat – 14: flexboxgrid.com

If you’re ready to build out your next site using flexbox you are probably going to want to use a grid. Well, you’re in luck because Kristofer Joseph has created Flexbox Grid with many of the features that you’re used to with other div based grids and more.

Flexbox Grid Features

More Info & Download

You can get more info and download Flexbox Grid here

What the :root Pseudo Class is and Why You Might Use it

The :root pseudo class, at first glance, is a little odd. It seems like it’s simply a replacement for using the HTML tag as a CSS selector. There’s a little bit more to it than that and in this article I will explain what the :root pseudo class is and why you might use it.

What’s Different Between :root and html?

For the most part the :root pseudo class will be referring to the html element. :root is the outer most or root element of the document which will always be the HTML tag when styling an HTML document.

The main difference between the two is that when styling HTML, SVG, or XML :root will refer to the outer most parent element of the document where as HTML is simply a CSS element selector that will always match the HTML tag. When using CSS to style SVG or XML files the root element will match whatever the parent node is within those files.

Another difference you should keep in mind when using :root is that it will have a higher specificity than HTML. :root will have a calculated specificity of 0 0 1 0 while HTML will have a specificity of 0 0 0 1. You can see this calculation in action using this handy specificity calculator by Keegan Street.

Some Examples

To better illustrate the differences I’ve provided a couple of examples below.

In an HTML Document

This is an example using :root in an HTML document where it will target the html tag.

CSS
:root { 
    background-color: red; 
}

See the Pen Untitled by Brian (@brianmtreese) on CodePen.

See the Pen EDmqA by Brian (@brianmtreese) on CodePen.

In an SVG

This is an example using :root in an embedded SVG in which it will target the outer svg tag.

HTML
<style media="screen">
    <![CDATA[ :root { background-color: #33cccc !important; }]]>
</style>

See the Pen Untitled by Brian (@brianmtreese) on CodePen.

See the Pen BEhCI by Brian (@brianmtreese) on CodePen.

In Conclusion

I’ve heard some people mention that you should actually be using :root instead of HTML by default now. I’m not sure if I’m sold on this yet but it does make sense if you consider the future of Web Components. Besides SVG and XML, Web Components will also use CSS. They will allow us to encapsulate modules of markup, functionality, and style into their own components. Using :root would allow us to easily target the root of those elements regardless of what their outer most tag is.


Browser Support

ie9 and above Chrome 1 and above Fire Fox 1 and aboveSafari 1 and above

The CSS :root pseudo class has pretty good browser support working in all modern browsers. Not supported in ie8 and below.


Sources

Quick Tip – 13: Quickly Apply Colors Using currentColor

If you’ve ever wanted to do something like set the borders on a container to the same color as the text within it you can easily do it using currentColor.

currentColor can be used for anything that accepts a color value like box-shadow, background-color, etc.

The CSS

CSS
.parent {
    color: red;
}

.child {
    border: solid 3px currentColor;
}

The Demo

My border should have a color of red which matches the color of my text

Browser Support

ie9 and above Chrome 1 and above Fire Fox 3.5 and above Safari 4 and above

CSS currentColor has pretty good browser support working in all modern browsers. Not supported in ie8 and below.

Things You May Not Know About CSS Backgrounds

I have been using CSS background properties for quite a few years and have only used what I have needed. There are some pretty cool things that can be done with backgrounds that I was not so familiar with. In this article I’ll highlight some of these not so common options.

background-origin

The background-origin property specifies where the viewing area for backgrounds applied to a given container will start. The background origin is based off of the top left corner. This property will not be applied if background-attachment is fixed.

border-box

The viewing area for backgrounds will begin at the outside edges of the container and will be displayed on a layer beneath the container’s border if one is applied.

CSS
div {
    background-origin: border-box;
}

Lorem ipsum dolor sit amet, consectetuer adipiscing elit. Aenean commodo ligula eget dolor. Aenean massa. Cum sociis natoque penatibus et magnis dis parturient montes, nascetur ridiculus mus. Donec quam felis, ultricies nec, pellentesque eu, pretium quis, sem. Nulla consequat massa quis enim.

padding-box

The viewing area for backgrounds will begin at the outside edges of the padding if any is applied and will not be displayed below the border if one is applied.

CSS
div {
    background-origin: padding-box;
}

Lorem ipsum dolor sit amet, consectetuer adipiscing elit. Aenean commodo ligula eget dolor. Aenean massa. Cum sociis natoque penatibus et magnis dis parturient montes, nascetur ridiculus mus. Donec quam felis, ultricies nec, pellentesque eu, pretium quis, sem. Nulla consequat massa quis enim.

content-box

The viewing area for backgrounds will begin at the edges of the content within the container.

CSS
div {
    background-origin: content-box;
}

Lorem ipsum dolor sit amet, consectetuer adipiscing elit. Aenean commodo ligula eget dolor. Aenean massa. Cum sociis natoque penatibus et magnis dis parturient montes, nascetur ridiculus mus. Donec quam felis, ultricies nec, pellentesque eu, pretium quis, sem. Nulla consequat massa quis enim.

inherit

The viewing area will be set based on that of its nearest parent with background-origin set. If one is not set on a parent element the default is padding-box.


background-size

The background-size property specifies the size for background images applied to a given container.

length/percentage

The background-size can be given a height and width in any length value px, em, %, etc. Percentages will be based on the dimensions of the parent container. Negative length values will not be applied.

CSS
div {
    background-size: 80% 50%;
}

Lorem ipsum dolor sit amet, consectetuer adipiscing elit. Aenean commodo ligula eget dolor. Aenean massa. Cum sociis natoque penatibus et magnis dis parturient montes, nascetur ridiculus mus. Donec quam felis, ultricies nec, pellentesque eu, pretium quis, sem. Nulla consequat massa quis enim.

auto

If explicitly setting a height and width on the background-size alters the aspect ratio/proportions of the image you can avoid this by picking either height or width to set explicitly and then set the other to auto.

CSS
div {
    background-size: 80% auto;
}

Lorem ipsum dolor sit amet, consectetuer adipiscing elit. Aenean commodo ligula eget dolor. Aenean massa. Cum sociis natoque penatibus et magnis dis parturient montes, nascetur ridiculus mus. Donec quam felis, ultricies nec, pellentesque eu, pretium quis, sem. Nulla consequat massa quis enim.

cover

The cover property will set the size of the image, maintaining its proportions, to be as small as it can be while both of its dimensions are greater than or equal to the dimensions of its container. When using cover there will be no area of the container that does not have the background image applied.

CSS
div {
    background-size: cover;
}

Lorem ipsum dolor sit amet, consectetuer adipiscing elit. Aenean commodo ligula eget dolor. Aenean massa. Cum sociis natoque penatibus et magnis dis parturient montes, nascetur ridiculus mus. Donec quam felis, ultricies nec, pellentesque eu, pretium quis, sem. Nulla consequat massa quis enim.

contain

The contain property is the opposite of the cover property. It will set the size of the image, maintaining its proportions, to be as large as it can be while both of its dimensions are less than or equal to the dimensions of its container.

CSS
div {
    background-size: contain;
}

Lorem ipsum dolor sit amet, consectetuer adipiscing elit. Aenean commodo ligula eget dolor. Aenean massa. Cum sociis natoque penatibus et magnis dis parturient montes, nascetur ridiculus mus. Donec quam felis, ultricies nec, pellentesque eu, pretium quis, sem. Nulla consequat massa quis enim.

background-clip

The background-clip property specifies the viewing area for backgrounds applied to a given container.

border-box

The viewing area for backgrounds will go to the outside edges of the container and will be displayed on a layer beneath the container’s border if one is applied.

CSS
div {
    background-clip: border-box;
}

Lorem ipsum dolor sit amet, consectetuer adipiscing elit. Aenean commodo ligula eget dolor. Aenean massa. Cum sociis natoque penatibus et magnis dis parturient montes, nascetur ridiculus mus. Donec quam felis, ultricies nec, pellentesque eu, pretium quis, sem. Nulla consequat massa quis enim.

padding-box

The viewing area for backgrounds will go to the outside edges of the padding if any is applied and will not be displayed below the border if one is applied.

CSS
div {
    background-clip: padding-box;
}

Lorem ipsum dolor sit amet, consectetuer adipiscing elit. Aenean commodo ligula eget dolor. Aenean massa. Cum sociis natoque penatibus et magnis dis parturient montes, nascetur ridiculus mus. Donec quam felis, ultricies nec, pellentesque eu, pretium quis, sem. Nulla consequat massa quis enim.

content-box

The viewing area for backgrounds will go to the edges of the content within the container.

CSS
div {
    background-clip: content-box;
}

Lorem ipsum dolor sit amet, consectetuer adipiscing elit. Aenean commodo ligula eget dolor. Aenean massa. Cum sociis natoque penatibus et magnis dis parturient montes, nascetur ridiculus mus. Donec quam felis, ultricies nec, pellentesque eu, pretium quis, sem. Nulla consequat massa quis enim.

inherit

The viewing area will be set based on that of its nearest parent with background-clip set. If one is not set on a parent element the default is border-box.


Browser Support

ie9 and above Chrome 31 and above Fire Fox 26 and above Safari 7 and above

These CSS background-image options have pretty good browser support working in the latest versions of all modern browsers. Not supported in ie8 and below.


Sources

AngularJS Overview for Web Designers

AngularJS is a newer JavaScript framework geared towards the creation and maintenance of single page web applications. It is considered to be a “toolset for building the framework most suited to your application development” meaning that, for the most part, you can choose the elements that you want to use and swap out those that you don’t want with other libraries/frameworks of your choice. It is built and maintained by Google and is open source with an MIT license.

Angular is written in pure JavaScript and is based on the model–view–controller (MVC) pattern making applications using it easier to develop and test. Angular uses two-way data-binding to synchronize the data between models and views.

For designers, besides working with HTML and CSS like we are used to and adjusting to working in an MVC pattern, we will likely be most interested in Angular directives and animations.

Directives

Angular contains components called Directives which are essentially “markers” on DOM elements like attributes, element names, or html classes. Angular will traverse the DOM and match these directives to attach specific behavior and/or transform the markup of itself and its children. They have no restrictions and can be added to any element in the DOM. ng-app is the most important directive because it bootstraps the application and runs Angular. It’s usually applied to the HTML tag or a div tag that wraps the page content.

HTML
<div ng-app>
    This is the Angular application content 
</div>

When using directives they can be written in two different ways using a dash (ng-model) or using a colon (data-ng:model). It is recommended to use a dash instead of colon because you can use “data-ng-model” to validate HTML in a validation tool.

You can use any from the set of built in directives or create your own custom directives if needed.

Directives Designers Will Use

There are quite a few directives that Angular provides out of the box but not all will be used by designers on a regular basis. I’ve chosen to sift through and find the ones that I’d use the most but you can find the whole list here.

ng-disabled

If true then the “disabled” attribute will be set on the element – Learn More

ng-checked

If true then the “checked” attribute will be set on the element – Learn More

ng-readonly

If true then the “readonly” attribute will be set on the element – Learn More

ng-selected

If true then the “selected” attribute will be set on the element – Learn More

ng-class

Allows you to dynamically set html classes on elements – Learn More

ng-class-odd

Allows you to dynamically set html classes on odd elements – Learn More

ng-class-even

Allows you to dynamically set html classes on even elements – Learn More

ng-cloak

Prevents the raw markup from displaying while your application is loading before AngularJS has had a chance to run and compile the html – Learn More

ng-click

An event that allows you to attach behavior when an element has been clicked – Learn More

ng-dblclick

An event that allows you to attach behavior when an element has been double clicked – Learn More

ng-mousedown

An event that allows you to attach behavior on mouse down – Learn More

ng-mouseup

An event that allows you to attach behavior on mouse up – Learn More

ng-mouseover

An event that allows you to attach behavior on mouse over – Learn More

ng-mouseenter

An event that allows you to attach behavior on mouse enter – Learn More

ng-mouseleave

An event that allows you to attach behavior on mouse leave – Learn More

ng-mousemove

An event that allows you to attach behavior on mouse move – Learn More

ng-keydown

An event that allows you to attach behavior on key down – Learn More

ng-keyup

An event that allows you to attach behavior on key up – Learn More

ng-keypress

An event that allows you to attach behavior on key press – Learn More

ng-focus

An event that allows you to attach behavior on an element when focused – Learn More

ng-blur

An event that allows you to attach behavior on an element when it has lost focus – Learn More

ng-copy

An event that allows you to attach behavior when copying – Learn More

ng-cut

An event that allows you to attach behavior when cutting – Learn More

ng-paste

An event that allows you to attach behavior when pasting – Learn More

ng-show

An event that allows you to show html based on the evaluation of an expression – Learn More

ng-hide

An event that allows you to hide html based on the evaluation of an expression – Learn More

ng-style

Allows you to conditionally set CSS on an element – Learn More


Animations

Angular provides animation hooks for certain directives that trigger CSS Transition animations, CSS Keyframe animations, or JavaScript Callback animations. Angular also includes animation detection support for custom animations when performing operations on DOM elements.

Angular animations are triggered on certain events like enter, leave, move, and class change. These animations are based completely on HTML classes and can be applied to any element with a class on it. These animations are also based on convention ng-(event) and ng-(event)-active.

CSS
.my-item.ng-enter {
    transition: height 0.5s;
}

.my-item.ng-enter.ng-enter-active {
    background-color: red;
}

JavaScript can be used to perform animations if you wish and these animations will use jQuery. However, It’s probably best not to use JavaScript if it can be avoided since it will likely add more code than necessary and can hinder performance to some degree.

If you want your animations tied to something other than one of the events enter, leave, or move, you can add them on add or remove of HTML classes. Angular will only recognize class changes if an expression or the ng-class directive is used.

HTML
<input type="button" value="set" ng-click="sizeVar='size-large'">
<input type="button" value="clear" ng-click="sizeVar='size-small'">
<div>
  <span ng-class="sizeVar">Animation Happens Here</span>
</div>

Directives With Animation Support

Not all of the out of the box directives support animations so below I’ve included the ones that do and the events that they have to trigger animations.

ng-repeat

Supported Events – enter, leave, and move

ng-view

Supported Events – enter and leave

ng-include

Supported Events – enter and leave

ng-switch

Supported Events – enter and leave

ng-if

Supported Events – enter and leave

ng-class

Supported Events – add and remove

ng-show

Supported Events – add and remove of the ng-hide class value

ng-hide

Supported Events – add and remove of the ng-hide class value


Animation Examples

To get more info and see real examples of animations in Angular check this out.


In Conclusion

From what I have read AngularJS is meant “to enable web-designers (non-programmers) to build simple app like websites” which looks to be possible but so far everything surrounding it like documentation, examples, tutorials, etc. seem to be very developer oriented. It can certainly do some cool stuff and I hope this article helps some of my fellow web designers begin to see how they can use it.

In theory it appears as though there is a lot of power in Angular but I’ve yet to use it on a project as of the time of writing. I guess you will just have to check back in a few months to see how it goes.


Browser Support

ie8 and above ChromeFire Fox Safari

Browser support for AngularJS is pretty good. If using version 1.2 it will work in ie7 and above. If using version 1.3 it will work in ie8 and above. I couldn’t find any info as to whether or not Angular supports Opera but my guess is that it does.


Sources

Getting Modular With Web Components

Modular is the new black when speaking in terms of the web. From the back-end perspective, developers have been building modular, object-oriented code for a long time now. Well, as web technologies and our development processes continue to improve, more and more of these back-end, programmatic philosophies are finding their way into front-end development.

The first real evidence of this was when CSS preprocessors like Less and Sass started popping up and gaining popularity. They do a lot of really cool stuff, but at their core they allow us to apply more of a programmatic approach to our CSS.

Then we had stuff like SMACSS and Object-Oriented CSS entering into the discussion. These methodologies are an attempt to organize and modularize our front-end code much like we do our back-end code. Now frameworks like Bootstrap and Foundation have become a solid starting point for front-end development combining both preprocessing and SMACSS/OOCSS principles. We also have things like pattern libraries becoming all the rage. They are showcases of these modules in action built to encourage consistency, re-use of common element styles, and make front-end code easier for us to maintain.

What are Web Components?

The newest tool on our modular front-end toolbox are Web Components. Gaining some real steam, many developers see them as our future. They are a new HTML5 standard to build reusable components for the web. They contain a set of custom elements, JavaScript, and styles unique to a specific component. A component can consist of anything as simple as a single button, input, or select to something as complex as a complete application. Web Components consist of the following:

Templates

The template element contains all of the mark up that will be used within a component. All code within the template will be parsed by the browser but not rendered until it is called elsewhere by JavaScript. This means that all external assets will not be loaded and all script tags won’t be processed by the browser until we want them to be.

HTML
<template>
    <div id="contentElement"></div>
</template>
<script>
    var t = document.querySelector('#contentElement');
    var contentElement = t.content.cloneNode(true);
    contentElement.innerHTML = 'This content will be inserted #contentElement';
    document.body.appendChild(contentElement);
</script>

Click here to see a nice example by front-end developer Nikos Zinas

Decorators

Decorators are not actually in the specification yet but they are intended to describe the presentation of Web Components.

HTML
<decorator id="items">
    <template>
        <style>
            .itemContent {
                padding: 10px;
            }
        </style>
        <div class="itemContent">
            <content></content>
        </div>
    </template>
</decorator>

The content element is required and is where the element’s children will get inserted.

There is a special decorator property that is used to apply styles via CSS.

CSS
.itemContainer {
    decorator: url(#items);
    background-color: red;
}

You would then add some html to the page that would call this template

HTML
<div class="itemContainer">
    This content will use the decorator 
</div>

Then, when the decorator is applied, the rendered mark up will look like this

HTML
<div class="itemContainer" style="background-color: red;">
    <div style="padding: 10px;">    
        This content will use the decorator
    </div> 
</div>

Decorators can do some other neat stuff, you can find out more here.

Custom Elements

Custom elements are exactly what you would think they are. They are new DOM or HTML elements that we create to make more sense for our code. Currently, most applications use a ton of div tags to do build out structure.

With the use of Custom Elements, this:

HTML
<div class="commentStream">
    <div class="commentStream__item">
        <div class="commentStream__avatar">
            <img src="/avatar.jpg" alt="My Avatar" />
        </div>
        <div class="commentStream__message">
            Yo, this is my message, what do you think?
        </div>
    </div>
</div>

Becomes this:

HTML
<commentstream-module>
    <commentstream-item>
        <commentstream-avatar>
            <img src="/avatar.jpg" alt="My Avatar" />
        </commentstream-avatar>
        <commentstream-message>
            Yo, this is my message, what do you think?
        </commentstream-message>
    </commentstream-item>
</commentstream-module>

Similarly to how the HTML5 shim creates DOM/HTML elements for the new HTML5 tags in older browsers that don’t support them, Custom Elements have to be instantiated with JavaScript as well.

They can also be created to extend other elements that already exist like buttons for example. You can then define new public properties and methods for button elements and then use your new tag where you need it.

You can get a more in-depth overview of what’s possible with Custom Elements here.

Shadow DOM

The Shadow DOM is very similar to the contents loaded within and iframe. They are sub tree nodes that form their own scope so that they are not affected by outside code. The Shadow DOM is separate from the HTML document so ids and styles will not interfere with those from the document. The Shadow DOM can be applied to any element using createShadowRoot().

With Shadow DOM this div:

HTML
<div id="content"></div>

Will get its own encapsulated Shadow DOM tree because of this code here:

JavaScript
var shadowHost = document.querySelector("#content");
var shadowRoot = shadowHost.createShadowRoot();
shadowRoot.textContent = "This is my content";

Many HTML5 elements like video and audio tags already have their own Shadow DOM and you can see it by enabling Shadow DOM in the Chrome developer tools. You can do this by bringing up the dev tools(F12), clicking on the gear icon, and then enabling “Show Shadow DOM”. Then you can inspect any ol’ HTML5 audio or video tag and see its Shadow DOM.

Imports

Imports allow you to load external files for decorators and elements as you would an external style sheet or JavaScript file

HTML
<link rel="import" href="module.html">

Polyfills

As I mentioned earlier, Web Components are still in the working draft phase so browser support is pretty spotty. Chrome and Fire Fox seem to support most of the spec. Google and Mozilla seem to really believe that Web Components are the future and both have created polyfills allowing us to start using this technology right now.

For more information, take a look at Google’s Polymer and Mozilla’s x-tag projects.


Browser Support – Templates

Chrome 31 and above Fire Fox 29 and above

Web Components Templates don’t have the best browser support working only in Chrome and Fire Fox.


Browser Support – Shadow DOM

Chrome 31 and above Fire Fox 29 and above

Web Components Shadow DOM doesn’t have the best browser support working only in Chrome and Fire Fox.


Sources

Pseudo-Classes vs. Pseudo-Elements

For the longest time the only pseudo selectors that we could use were :link, :hover, :visited and :active and they could only be applied to a tags. As long as we were intending to support ie6 that was all we could do. As we’ve adopted philosophies like progressive enhancement, graceful degradation, or dropped support for ie6, 7, and 8 we have seen the landscape of CSS selectors change dramatically.

As I have began using more pseudo selectors I’ve found myself using the terms pseudo-classes and pseudo-elements interchangeably, which I’ve known to be wrong. In order to correct this I’ve decided to explore the differences between the two.

Pseudo-Classes

A pseudo-class is a keyword that can be added to a selector based on a special state of the selected item. They are unique in that they can be actual elements in the DOM or they can be based on states that are triggered when certain actions occur such as :hover, :visited, :checked, etc.

How They Are Used

CSS
li {
    border-top: solid 1px gray;
}

li:first-child {
    border: none;
}

:active

Matches when an element is being activated by the user — Learn More

ie4 and above Chrome 1 and above Fire Fox 1 and above Safari 1 and above

:checked

Represents any radio, checkbox, or option in a select element that is checked or toggled to an on state — Learn More

ie9 and above Chrome 1 and above Fire Fox 1 and above Safari 3.1 and above

:default

Represents any user interface element that is the default among a group of similar elements — Learn More

Chrome 10 and above Fire Fox 4 and above Safari 5 and above

:dir()

Matches elements based on the directionality of the text contained in it — Learn More

Fire Fox 17 and above

:disabled

Represents any disabled element. An element is disabled if it can’t be activated (e.g. selected, clicked on or accept text input) or accept focus — Learn More

ie9 and above Chrome 1 and above Fire Fox 1 and above Safari 3.1 and above

:empty

Represents any element that has no children at all. Only element nodes and text (including whitespace) are considered — Learn More

ie9 and above Chrome 1 and above Fire Fox 1 and above Safari 3.1 and above

:enabled

Represents any enabled element. An element is enabled if it can be activated (e.g. selected, clicked on or accept text input) or accept focus — Learn More

ie9 and above Chrome 1 and above Fire Fox 1 and above Safari 3.1 and above

:first

Describes the styling of the first page when printing a document — Learn More

ie8 and above

:first-child

Represents any element that is the first child element of its parent — Learn More

ie7 and above Chrome 4 and above Fire Fox 3 and above Safari 4 and above

:first-of-type

Represents the first sibling of its type in the list of children of its parent element — Learn More

ie9 and above Chrome 1 and above Fire Fox 3.5 and above Safari 3.2 and above

:fullscreen

Applies to any element that’s currently being displayed in full-screen mode — Learn More

ie11 and above Chrome 15 and above Fire Fox 9 and above Safari 6 and above

:focus

Applied when a element has received focus, either from the user selecting it with the use of a keyboard or by activating with the mouse (e.g. a form input) — Learn More

ie8 and above Chrome 1 and above Fire Fox 1 and above Safari 1 and above

:hover

Matches when the user designates an element with a pointing device, but does not necessarily activate it — Learn More

ie7 and above Chrome 0.2 and above Fire Fox 1 and above Safari 2.0.4 and above

:indeterminate

Represents any input type=“checkbox” element whose indeterminate DOM property is set to true by JavaScript — Learn More

ie9 and above Chrome 6 and above Fire Fox 3.6 and above Safari 3 and above

:invalid

Represents any input or form element whose content fails to validate according to the input’s type setting — Learn More

ie10 and above Chrome 10 and above Fire Fox 4 and above Safari 5 and above

:lang()

Matches elements based on the language the element is determined to be in — Learn More

ie8 and above Chrome 1 and above Fire Fox 1 and above Safari 3.1 and above

:last-child

Represents any element that is the last child element of its parent — Learn More

ie9 and above Chrome 1 and above Fire Fox 1 and above Safari 3.2 and above

:last-of-type

Represents the last sibling of its type in the list of children of its parent element — Learn More

ie9 and above Chrome 1 and above Fire Fox 3.5 and above Safari 3.2 and above

:left

Matches any left page when printing a page. It allows to describe the styling of left-side pages — Learn More

ie8 and above

:link

Lets you select links inside elements — Learn More

Safari 1 and above

:not()

A functional notation taking a simple selector as an argument. It matches an element that is not represented by the argument. Must not contain another negation selector, or any pseudo-elements — Learn More

ie9 and above Chrome 1 and above Fire Fox 1 and above Safari 3.2 and above

:nth-child

Matches an element that has siblings before it in the document tree, for a given positive or zero value, and has a parent element — Learn More

ie9 and above Chrome 1 and above Fire Fox 1 and above Safari 3.1 and above

:nth-last-child

Matches elements that have siblings after them in the document tree, for a given positive or zero value, and have a parent element — Learn More

ie9 and above Chrome 1 and above Fire Fox 1 and above Safari 3.1 and above

:nth-last-of-type

Matches the last element that has siblings with the same element name after it in the document tree, for a given positive or zero value, and has a parent element — Learn More

ie9 and above Chrome 4 and above Fire Fox 3.5 and above Safari 3.2 and above

:nth-of-type

Matches an element that has siblings with the same element name before it in the document tree, for a given positive or zero value, and has a parent element — Learn More

ie9 and above Chrome 1 and above Fire Fox 3.5 and above Safari 3.1 and above

:only-child

Represents any element which is the only child of its parent — Learn More

ie9 and above Chrome 2 and above Fire Fox 1.5 and above Safari 3.1 and above

:only-of-type

Represents any element that has no siblings of the given type — Learn More

ie9 and above Chrome 1 and above Fire Fox 3.5 and above Safari 3.2 and above

:optional

Represents any input element that does not have the required attribute set on it — Learn More

ie10 and above Chrome 10 and above Fire Fox 4 and above Safari 5 and above

:read-write

Matches when an element is editable by user like text input element — Learn More

ie9 and above Supported in Chrome Supported in Fire Fox Supported in Safari

:required

Represents any input element that has the required attribute set on it — Learn More

ie10 and above Chrome 10 and above Fire Fox 4 and above Safari 5 and above

:right

Matches any right page when printing a page. It allows to describe the styling of right-side page — Learn More

ie8 and above

:root

Matches the root element of a tree representing the document — Learn More

ie9 and above Chrome 1 and above Fire Fox 1 and above Safari 1 and above

:scope

Matches the elements that are a reference point for selectors to match against — Learn More

Chrome 20 and above Fire Fox 21 and above Safari 7 and above

:target

Represents the unique element, if any, with an id matching the fragment identifier of the URI of the document — Learn More

ie9 and above Chrome 1 and above Fire Fox 1.3 and above Safari 1.3 and above

:valid

Represents any input element whose content validates correctly according to the input’s type setting — Learn More

ie10 and above Chrome 10 and above Fire Fox 4 and above Safari 5 and above

:visited

Lets you select only links that have been visited — Learn More

ie3.5 and above Chrome 1 and above Fire Fox 1 and above Safari 1 and above

Pseudo-Elements

Like a pseudo-class, a pseudo-element is a keyword that can be added to a selector. Where they differ is that a pseudo-class does not apply to a special state but rather a portion of html that doesn’t exist in the DOM like :before or is not contained within a tag like :first-letter.

Another difference is that as part of the CSS3 spec, in an attempt to differentiate pseudo-classes from pseudo selectors, use of double colons(::) was allowed. Most browsers support both single and double colons for pseudo-elements.

How They Are Used

CSS
li::after {
    clear: both;
}

::after

Matches a virtual last child of the selected element. Typically used to add cosmetic content to an element, by using the content CSS property — Learn More

ie8 and above Supported in Chrome Fire Fox 1 and above Safari 4 and above

::before

Creates a pseudo-element that is the first child of the element matched. Typically used to add cosmetic content to an element, by using the content CSS property — Learn More

ie8 and above Supported in Chrome Fire Fox 1 and above Safari 4 and above

::first-letter

Selects the first letter of the first line of a block, if it is not preceded by any other content (such as images or inline tables) on its line — Learn More

ie9 and above Chrome 1 and above Fire Fox 1 and above Safari 1 and above

::first-line

Applies styles only to the first line of an element — Learn More

ie9 and above Chrome 1 and above Fire Fox 1 and above Safari 1 and above

::selection

Applies rules to the portion of a document that has been highlighted (e.g., selected with the mouse or another pointing device) by the user — Learn More

ie9 and above Chrome 1 and above Fire Fox 1 and above Safari 1.1 and above

Sources

Brian Treese