Tag Archives: element

Thumbnail

The Holy Grail Of Reusable Components: Custom Elements, Shadow DOM, And NPM




The Holy Grail Of Reusable Components: Custom Elements, Shadow DOM, And NPM

Oliver Williams



For even the simplest of components, the cost in human-labour may have been significant. UX teams do usability testing. An array of stakeholders have to sign off on the design.

Developers conduct AB tests, accessibility audits, unit tests and cross-browser checks. Once you’ve solved a problem, you don’t want to repeat that effort. By building a reusable component library (rather than building everything from scratch), we can continuously utilize past efforts and avoid revisiting already solved design and development challenges.


A screenshot of Google’s material components website – showing various components.


Large preview

Building an arsenal of components is particularly useful for companies such as Google that own a considerable portfolio of websites all sharing a common brand. By codifying their UI into composable widgets, larger companies can both speed up development time and achieve consistency of both visual and user-interaction design across projects. There’s been a rise in interest in style guides and pattern libraries over the last several years. Given multiple developers and designers spread over multiple teams, large companies seek to attain consistency. We can do better than simple color swatches. What we need is easily distributable code.

Sharing And Reusing Code

Manually copy-and-pasting code is effortless. Keeping that code up-to-date, however, is a maintenance nightmare. Many developers, therefore, rely on a package manager to reuse code across projects. Despite its name, the Node Package Manager has become the unrivalled platform for front-end package management. There are currently over 700,000 packages in the NPM registry and billions of packages are downloaded every month. Any folder with a package.json file can be uploaded to NPM as a shareable package. While NPM is primarily associated with JavaScript, a package can include CSS and markup. NPM makes it easy to reuse and, importantly, update code. Rather than needing to amend code in myriad places, you change the code only in the package.

The Markup Problem

Sass and Javascript are easily portable with the use of import statements. Templating languages give HTML the same ability — templates can import other fragments of HTML in the form of partials. You can write the markup for your footer, for example, just once, then include it in other templates. To say there exists a multiplicity of templating languages would be an understatement. Tying yourself to just one severely limits the potential reusability of your code. The alternative is to copy-and-paste markup and to use NPM only for styles and javascript.

This is the approach taken by the Financial Times with their Origami component library. In her talk “Can’t You Just Make It More like Bootstrap?” Alice Bartlett concluded “there is no good way to let people include templates in their projects”. Speaking about his experience of maintaining a component library at Lonely Planet, Ian Feather reiterated the problems with this approach:

“Once they copy that code they are essentially cutting a version which needs to be maintained indefinitely. When they copied the markup for a working component it had an implicit link to a snapshot of the CSS at that point. If you then update the template or refactor the CSS, you need to update all versions of the template scattered around your site.”

A Solution: Web Components

Web components solve this problem by defining markup in JavaScript. The author of a component is free to alter markup, CSS, and Javascript. The consumer of the component can benefit from these upgrades without needing to trawl through a project altering code by hand. Syncing with the latest changes project-wide can be achieved with a terse npm update via terminal. Only the name of the component and its API need to stay consistent.

Installing a web component is as simple as typing npm install component-name into a terminal. The Javascript can be included with an import statement:

<script type="module">
import './node_modules/component-name/index.js';
</script>

Then you can use the component anywhere in your markup. Here is a simple example component that copies text to the clipboard.

See the Pen Simple web component demo by CSS GRID (@cssgrid) on CodePen.

A component-centric approach to front-end development has become ubiquitous, ushered in by Facebook’s React framework. Inevitably, given the pervasiveness of frameworks in modern front-end workflows, a number of companies have built component libraries using their framework of choice. Those components are reusable only within that particular framework.


A component from IBM’s Carbon Design System


A component from IBM’s Carbon Design System. For use in React applications only. Other significant examples of component libraries built in React include Atlaskit from Atlassian and Polaris from Shopify. (Large preview)

It’s rare for a sizeable company to have a uniform front-end and replatorming from one framework to another isn’t uncommon. Frameworks come and go. To enable the maximum amount of potential reuse across projects, we need components that are framework agnostic.


A screenshot from npmjs.com showing components that do that same thing built exclusively for particular javascript frameworks.


Searching for components via npmjs.com reveals a fragmented Javascript ecosystem. (Large preview)


A graph charting the popularity of frameworks over time. Ember, Knockout and Backbone have plunged in popularity, replaced by newer offerings.


The ever-changing popularity of frameworks over time. (Large preview)

“I have built web applications using: Dojo, Mootools, Prototype, jQuery, Backbone, Thorax, and React over the years…I would love to have been able to bring that killer Dojo component that I slaved over with me to my React app of today.”

Dion Almaer, Director of Engineering, Google

When we talk about a web component, we are talking about the combination of a custom element with shadow DOM. Custom Elements and shadow DOM are part of both the W3C DOM specification and the WHATWG DOM Standard — meaning web components are a web standard. Custom elements and shadow DOM are finally set to achieve cross-browser support this year. By using a standard part of the native web platform, we ensure that our components can survive the fast-moving cycle of front-end restructuring and architectural rethinks. Web components can be used with any templating language and any front-end framework — they’re truly cross-compatible and interoperable. They can be used everywhere from a WordPress blog to a single page application.


The Custom Elements Everywhere project by Rob Dodson documents the interoperability of web components with various client-side Javascript frameworks.


The Custom Elements Everywhere project by Rob Dodson documents the interoperability of web components with various client-side Javascript frameworks. React, the outlier here, will hopefully resolve these issues with React 17. (Large preview)

Making A Web Component

Defining A Custom Element

It’s always been possible to make up tag-names and have their content appear on the page.

<made-up-tag>Hello World!</made-up-tag>

HTML is designed to be fault tolerant. The above will render, even though it’s not a valid HTML element. There’s never been a good reason to do this — deviating from standardized tags has traditionally been a bad practice. By defining a new tag using the custom element API, however, we can augment HTML with reusable elements that have built-in functionality. Creating a custom element is much like creating a component in React — but here were extending HTMLElement.

class ExpandableBox extends HTMLElement 
      constructor() 
        super()
      
    }

A parameter-less call to super() must be the first statement in the constructor. The constructor should be used to set up initial state and default values and to set up any event listeners. A new custom element needs to be defined with a name for its HTML tag and the elements corresponding class:

customElements.define('expandable-box', ExpandableBox)

It’s a convention to capitalize class names. The syntax of the HTML tag is, however, more than a convention. What if browsers wanted to implement a new HTML element and they wanted to call it expandable-box? To prevent naming collisions, no new standardized HTML tags will include a dash. By contrast, the names of custom elements have to include a dash.

customElements.define('whatever', Whatever) // invalid
customElements.define('what-ever', Whatever) // valid

Custom Element Lifecycle

The API offers four custom element reactions — functions that can be defined within the class that will automatically be called in response to certain events in the lifecycle of a custom element.

connectedCallback is run when the custom element is added to the DOM.

connectedCallback() 
    console.log("custom element is on the page!")

This includes adding an element with Javascript:

document.body.appendChild(document.createElement("expandable-box")) //“custom element is on the page”

as well as simply including the element within the page with a HTML tag:

<expandable-box></expandable-box> // "custom element is on the page"

Any work that involves fetching resources or rendering should be in here.

disconnectedCallback is run when the custom element is removed from the DOM.

disconnectedCallback() 
    console.log("element has been removed")

document.querySelector("expandable-box").remove() //"element has been removed"

adoptedCallback is run when the custom element is adopted into a new document. You probably don’t need to worry about this one too often.

attributeChangedCallback is run when an attribute is added, changed, or removed. It can be used to listen for changes to both standardized native attributes like disabled or src, as well as any custom ones we make up. This is one of the most powerful aspects of custom elements as it enables the creation of a user-friendly API.

Custom Element Attributes

There are a great many HTML attributes. So that the browser doesn’t waste time calling our attributeChangedCallback when any attribute is changed, we need to provide a list of the attribute changes we want to listen for. For this example, we’re only interested in one.

static get observedAttributes() 
            return ['expanded']
        

So now our attributeChangedCallback will only be called when we change the value of the expanded attribute on the custom element, as it’s the only attribute we’ve listed.

HTML attributes can have corresponding values (think href, src, alt, value etc) while others are either true or false (e.g. disabled, selected, required). For an attribute with a corresponding value, we would include the following within the custom element’s class definition.

get yourCustomAttributeName() 
  return this.getAttribute('yourCustomAttributeName');

set yourCustomAttributeName(newValue) 
  this.setAttribute('yourCustomAttributeName', newValue);

For our example element, the attribute will either be true or false, so defining the getter and setter is a little different.

get expanded() 
  return this.hasAttribute('expanded')

        
// the second argument for setAttribute is mandatory, so we’ll use an empty string
set expanded(val) 
  if (val) 
    this.setAttribute('expanded', '');
  
  else 
    this.removeAttribute('expanded')
  
}

Now that the boilerplate has been dealt with, we can make use of attributeChangedCallback.

attributeChangedCallback(name, oldval, newval) 
  console.log(`the $name attribute has changed from $oldval to $newval!!`);
  // do something every time the attribute changes
}

Traditionally, configuring a Javascript component would have involved passing arguments to an init function. By utilising the attributeChangedCallback, its possible to make a custom element that’s configurable just with markup.

Shadow DOM and custom elements can be used separately, and you may find custom elements useful all by themselves. Unlike shadow DOM, they can be polyfilled. However, the two specs work well in conjunction.

Attaching Markup And Styles With Shadow DOM

So far, we’ve handled the behavior of a custom element. In regard to markup and styles, however, our custom element is equivalent to an empty unstyled <span>. To encapsulate HTML and CSS as part of the component, we need to attach a shadow DOM. It’s best to do this within the constructor function.

class FancyComponent extends HTMLElement 
        constructor() 
            super()
            var shadowRoot = this.attachShadow(mode: 'open')
            shadowRoot.innerHTML = `<h2>hello world!</h2>`
            }

Don’t worry about understanding what the mode means — its boilerplate you have to include, but you’ll pretty much always want open. This simple example component will just render the text “hello world”. Like most other HTML elements, a custom element can have children — but not by default. So far the above custom element we’ve defined won’t render any children to the screen. To display any content between the tags, we need to make use of a slot element.

shadowRoot.innerHTML = `
<h2>hello world!</h2>
<slot></slot>
`

We can use a style tag to apply some CSS to the component.

shadowRoot.innerHTML = 
`<style>
p 
color: red;

</style>
<h2>hello world!</h2>
<slot>some default content</slot>`

These styles will only apply to the component, so we are free to make use of element selectors without the styles affecting anything else of the page. This simplifies writing CSS, making naming conventions like BEM unnecessary.

Publishing A Component On NPM

NPM packages are published via the command line. Open a terminal window and move into a directory that you would like to turn into a reusable package. Then type the following commands into the terminal:

  1. If your project doesn’t already have a package.json, npm init will walk you through generating one.
  2. npm adduser links your machine to your NPM account. If you don’t have a preexisting account, it will create a new one for you.
  3. npm publish

NPM packages are published via the command line


Large preview

If all’s gone well, you now have a component in the NPM registry, ready to be installed and used in your own projects — and shared with the world.


An example of a component in the NPM registry, ready to be installed and used in your own projects.


Large preview

The web components API isn’t perfect. Custom elements are currently unable to include data in form submissions. The progressive enhancement story isn’t great. Dealing with accessibility isn’t as easy as it should be.

Although originally announced in 2011, browser support still isn’t universal. Firefox support is due later this year. Nevertheless, some high-profile websites (like Youtube) are already making use of them. Despite their current shortcomings, for universally shareable components they’re the singular option and in the future we can expect exciting additions to what they have to offer.

Smashing Editorial
(il, ra, yk)


See the original article here:

The Holy Grail Of Reusable Components: Custom Elements, Shadow DOM, And NPM

Thumbnail

Making Avengers ID Card In HTML And CSS




Making Avengers ID Card In HTML And CSS

Kunal Sarkar



Let’s suppose Tony Stark would like to redesign the ID cards of the Avengers, and he needs our help to create them in HTML and CSS. So, how can we help? In this tutorial, we’ll be using Flexbox to create the desired layout while diving into nested flexboxes for some advanced layouts. We will also be using rounded as well as transparent borders to create sci-fi arcs in CSS, and then animating them by using CSS animations around the picture of the Avenger. Last but not least, we’ll be using the box-shadow and text-shadow properties to give our ID card a final sci-fi touch.

By the end of the tutorial, we will build a sci-fi animated Avengers ID card, and also learn the basics of Flexbox, nested Flexbox, CSS animations, borders, shadows, and many other frequently used CSS properties.

Here’s how our final Avengers ID card will look like:

See the Pen Avengers ID Card by Kunal Sarkar (@supersarkar) on CodePen.

Let’s get started!

Full-Page Background

We need a div that covers the entire screen. We will use this div as the background to place the ID card:

<div class="id-card-wrapper">
</div>

Let’s make the div cover the entire page and give a dark background:

body 
  margin:0px;

.id-card-wrapper 
  height: 100vh;
  width:100%;
  background-color: #122023;

Why use 100vh and not 100% for height?

If you look closely, you will notice that we used 100% for width, but 100vh for height. The vh unit stands for “viewport height”. It is a viewport unit, some other viewport units are: vw, vmin, and vmax.

So, why should we use 100vh instead of 100% for the height? Well, a % based dimension is relative to its parent element. So, if we set the height of the id-card-wrapper to 100%, that would mean it will make the height of id-card-wrapper cover 100% of the height of its parent element (which is the body element).

The problem is — by default — the body element doesn’t cover entire screen’s height. The width of the body element is by default 100% that’s why we can use width: 100% on id-card-wrapper, but since the height is not 100% by default the same won’t work for height.

Since a viewport unit is relative to the viewport, not the parent element, setting the height to 100vh will make the element cover entire height of the visible area (viewport), regardless of the parent’s dimensions.

Note: If you want to dive deeper into the viewport units, checkout this Fun with Viewport Units article on CSS-Tricks. One more thing, there are many ways to create a full page background, Chris Coyier lists them well in this post.

Why margin: 0px On Body?

The browsers by default display some margin around the body. If we don’t set this margin to 0, we will get a white gap around the id-card-wrapper div.

Centering Using Flexbox

There are many ways to center. Now that our full-page background is ready, let’s create the div that will contain our ID Card. We will put only “Test” as content, and build the layout first:

<div class="id-card-wrapper">
    <div class="id-card">
        Test
    </div>
</div>

And add some styles to it:

.id-card 
  border: 2px solid #0AE0DF;
  max-width: 30em;
  margin: auto;
  color: #fff;
  padding: 1em;

We are using the border property to give a 2px solid border of #0AE0DF color to the id-card element.

Since a “div” is a block element, it will cover the entire width of the parent element by default. But we don’t want it to go beyond 30em, so we’ll set the max-width property to 30em.

Wait, What Is em Again?

Here’s what W3C has to say about the “em” unit:

“The em is simply the font size. In an element with a 2in font, 1em thus means 2in.”

This means that if your browser has a default font size of 14px, then 30em will be equal to 30×14 = 420px.

But, why use em unit instead of px?

Look, the em unit is relative to the font size. Let’s suppose you are using a browser with 14px default font size. Now if someone views your project from another browser that has 16px as default font size, then guess what would happen?

The content inside will need more space, but your div has a fixed width, i.e. the content will either spill out or break the layout.

It’s always a good idea to have dimensions that scale along with the content, instead of fixing it to arbitrary pixels.

Why Doesn’t margin: auto Center The div Vertically?**

We already know that we can center a block element horizontally using margin: auto, but it doesn’t work for vertical centering.


Screenshot of a horizontally centered element


Auto margin centers the element horizontally

What if I told you that margin: auto works vertically, too? Actually, in normal layout mode, it doesn’t. But in new layout modes like Flexbox, the margin: auto works for vertical centering, too. Go ahead and make the id-card-wrapper a flexbox to see it yourself:

.id-card-wrapper 
  height: 100vh;
  width:100%;
  background-color: #122023;
  display: flex;

Output:


Screenshot of a horizontally and vertically centered element


Auto margin centers the element horizontally and vertically if the element is a flex-item

As you can see, our id-card div is now centered horizontally and vertically. We simply set display: flex on the id-card-wrapper div. When you set display: flex to an element, that element becomes a flex-container and its child elements become flex-items. Check out “Basic Concepts Of Flexbox” on MDN.

Okay, this did center our element, but why did it lose its width? The id-card div is a block element, and since block elements are by default 100% wide, why did the div lose this block level behavior when it became a flex-item?

Actually, it hasn’t lost its block behavior. What’s happening is, as soon as the div comes into the flexbox context, the flexbox algorithm notes that the div doesn’t have any width property set to it (we are giving it only max-width), and then it sets the initial width to 0.

We can change this behavior by explicitly defining the initial width of the element using the [flex-basis](https://developer.mozilla.org/en-US/docs/Web/CSS/flex-basis) property, like this:

.id-card 
  flex-basis: 100%;
  border: 2px solid #0AE0DF;
  max-width: 30em;
  margin: auto;
  color: #fff;
  padding: 1em;

And now the result looks just as expected:


Screenshot of a flex-item set with flex-basis set to 100%


The initial width of the flex-item set to 100% using “flex-basis”

Nested Flexboxes

Now our id-card div is ready for content. Let’s create a profile-row div and two sections in it dp and desc. The dp div will contain the profile photo of the Avenger while the desc div will contain the description of that Avenger:

<div class="id-card-wrapper">
    <div class="id-card">
        <div class="profile-row">
            <div class="dp">
                Test
            </div>
            <div class="desc">
                Test desc
            </div>
        </div>
    </div>
</div>

We know that the id-card div is a flex-item, but the div we just created inside id-card (the profile-row div) isn’t a flex-item. Yes, only the direct decedents of the flex-containers become flex-items, but not the grandchildren.

Therefore, profile-row is a normal div, and we will make it a flex-container by setting display: flex to it. This will make its child elements, dp and desc, flex-items:

.profile-row 
  display: flex;

Now we can use the flex-basis property to make the dp div 33.3% wide and the desc div 66.6% wide:

.profile-row .dp 
  flex-basis: 33.3%;

.profile-row .desc 
  flex-grow: 66.6%;

Here’s what we get:


Screenshot of two flex-items in a row with 33.3% and 66.6% width


We can define how much space the elements would occupy using the “flex-basis” property.

Profile Image

For the profile image, we will use a cute Iron Man picture for Stark’s ID card (download it here). Include the image using img tag inside the dp div:

<div class="id-card-wrapper">
    <div class="id-card">
        <div class="profile-row">
            <div class="dp">
                <img src="img/iron-man-dp.jpg">
            </div>
            <div class="desc">
                Test desc
            </div>
        </div>
    </div>
</div>

And give some styles to it:

.profile-row .dp img 
  max-width: 100%;
  border-radius: 50%;

.profile-row .desc 
  padding: 1em;

We set max-width: 100% for the img element because the img element by default displays the image in its original resolution.

If the image is 500px×500px then it will be displayed in that dimension. But we don’t want that. Instead, we want the image to be only as wide as the dp div, that’s why we set its max-width to 100%.

Also, we set the border-radius property to 50%. We are doing this to display the image as a circle:


Screenshot of Iron Man rounded image with demo text


We don’t make the img element a flex-item, but rather put it inside a flex-item.

Making Arcs In CSS

Eventually, Tony visits us while we’re still working on this ID card, and says that this doesn’t look sci-fi enough. Alright, no problem. Let’s make it more sci-fi. We can make two arcs rotate around the image by inserting the first arc dp-arc-inner inside the dp element:

<div class="id-card-wrapper">
    <div class="id-card">
        <div class="profile-row">
            <div class="dp">
                <div class="dp-arc-inner"></div>
                <img src="img/iron-man-dp.jpg">
            </div>
            <div class="desc">
                Test desc
            </div>
        </div>
    </div>
</div>

Position it in CSS:

.profile-row .dp 
  flex-basis: 33.3%;
  position: relative;

.profile-row .dp img 
  max-width: 100%;
  border-radius: 50%;
  display: block;

.profile-row .dp .dp-arc-inner 
  position: absolute;
  width: 100%;
  height: 100%;
  border: 6px solid #0AE0DF;
  top: -6px;
  left: -6px;

We want the arc div to overlap on the dp div. The only problem is that elements don’t overlap in HTML. However, if we set the position of an element as absolute then that element is taken out of the normal flow of the document and we can set its position as we desire.

The default positioning of HTML elements is static. We set position: absolute on dp-arc-inner to make it absolutely positioned. Now we can use left, top, bottom, and right properties to set its position.

One caution: The left, top, bottom, and right properties are relative the first parent element in the hierarchy which is “relatively” positioned. That’s why we’ve set position: relative on the dp div. If we don’t do this, the left, top, bottom, and right properties will be set respectively to the screen, not the dp element.

One more thing: we are setting display: block on the img element. Why? Because img elements are inline-block by default, and inline-block elements display a tiny gap on its sides and bottom.

This gap generally doesn’t cause any problem, but a little gap around the image in our case will offset the arc’s position. So we set the img element as block element.

Next, let’s make the dp-arc-inner div look like an arc:

.profile-row .dp .dp-arc-inner 
  position: absolute;
  width: 100%;
  height: 100%;
  border: 6px solid transparent;
  border-top-color: #0AE0DF;
  border-radius: 50%;
  top: -6px;
  left: -6px;

What we are doing is, instead of setting the border for all the sides with #0AE0DF color, we are setting all the sides as transparent, and then giving only the top border the color #0AE0DF. Then we set the border-radius: 50% to make it round:


Screenshot of Iron Man’s rounded image surrounded with an arc covering it


The negative margins offsets the width of the border we gave to the arc

Okay, let’s create one more arc, dp-arc-outer:

<div class="id-card-wrapper">
    <div class="id-card">
        <div class="profile-row">
            <div class="dp">
                <div class="dp-arc-outer"></div>
                <div class="dp-arc-inner"></div>
                <img src="img/iron-man-dp.jpg">
            </div>
            <div class="desc">
                Test desc
            </div>
        </div>
    </div>
</div>

And style it the same way:

.profile-row .dp .dp-arc-outer 
  position: absolute;
  width: calc(100% + 12px);
  height: calc(100% + 12px);
  border: 6px solid transparent;
  border-bottom-color: #0AE0DF;
  border-radius: 50%;
  top: -12px;
  left: -12px;

Wow, what’s that calc thing there?

Calc is a CSS function that calculates the mathematical expression given to it. Look, we had the inner arc with width and height of 100% and a border of 6px, right? That makes the inner arc’s total width 6px + 100% + 6px.

Now if we want the outer arc to be bigger than the inner arc then we need some way to make it 100% + 12px wide. This is where the calc() function comes to the rescue.

Also, notice that we are using border-bottom-color for this arc since we want the arc to display on the bottom.

Output:


Screenshot of Iron Man’s rounded image surrounded with two arcs covering it


The calc function adds 12px to create the 6px gap between the arc and the image

Animating The Arcs

Now that our arcs are ready, let’s make them rotate around the image. We can do this with the help of CSS animations.

Any animation requires three basic things:

  1. The start state of the animation,
  2. The end state of the animation,
  3. How long it should take to go from start to end state (speed of the animation).

We can provide these data in CSS like this:

.profile-row .dp .dp-arc-inner 
  position: absolute;
  width: 100%;
  height: 100%;
  border: 6px solid transparent;
  border-top-color: #0AE0DF;
  border-radius: 50%;
  top: -6px;
  left: -6px;

  animation-duration: 2s;
  animation-name: rotate-clock;

@keyframes rotate-clock 
  from 
    transform: rotate(0deg);
  
  to 
    transform: rotate(360deg);
  
}

We use @keyframes to define the animation. The from and to keywords are used to set the start and end state of the animation.

In the start state, we are rotating the arc 0-degree using transform: rotate(0deg), and in the end state we are rotating the arc 360-degree using transform: rotate(360deg).

To use this animation on an element, we need to give the name of the animation (rotate-clock in our case) to the animation-name property of that element. That’s what we are doing with animation-name: rotate-clock .

We also need to know how long it should take the animation to complete. We can do this by setting animation-duration property to 2s.

See the Pen Avengers ID Card – 1 by Kunal Sarkar (@supersarkar) on CodePen.

You will notice two problems in the output. One, the arc is rotated only one time, we want it to keep rotating, and two, the animation is not linear. The animation is fast at beginning and end, we want it to rotate with same speed throughout the animation.

To solve these problems, we will use the animation-iteration-count property to keep the animation repate itself infinite times, and animation-timing-function property to get a linear animation:

.profile-row .dp .dp-arc-inner 
  position: absolute;
  width: 100%;
  height: 100%;
  border: 6px solid transparent;
  border-top-color: #0AE0DF;
  border-radius: 50%;
  top: -6px;
  left: -6px;

  animation-duration: 2s;
  animation-name: rotate-clock;
  animation-iteration-count: infinite;
  animation-timing-function: linear;

See the Pen Avengers ID Card – 2 by Kunal Sarkar (@supersarkar) on CodePen.

Okay, the inner arc is now rotating as expected. Now let’s animate the outer arc in the same way, but in the opposite direction:

.profile-row .dp 
  flex-basis: 33.3%;
  position: relative;
  margin: 24px;

.profile-row .dp .dp-arc-outer 
  position: absolute;
  width: calc(100% + 12px);
  height: calc(100% + 12px);
  border: 6px solid transparent;
  border-bottom-color: #0AE0DF;
  border-radius: 50%;
  top: -12px;
  left: -12px;

  animation-duration: 2s;
  animation-name: rotate-anticlock;
  animation-iteration-count: infinite;
  animation-timing-function: linear;

@keyframes rotate-anticlock 
  from 
    transform: rotate(0deg);
  
  to 
    transform: rotate(-360deg);
  
}

We only changed the to state for the outer arc. Instead of rotating it a positive 360 degree, we rotated it a negative 360 degree, to get an anti-clockwise animation.

Note that we also added 24px margin to the .dp so that it doesn’t get too congested. Here’s what our result looks like now:

See the Pen Avengers ID Card – 3 by Kunal Sarkar (@supersarkar) on CodePen.

Using A Sci-Fi Google Font

Tony visits again, and this time he is happy with where we are heading. Only one thing though: he asks to use a sci-fi font.

Not a problem. Let’s use the Orbitron font from Google Fonts. Google Fonts gives a wealth of fonts for free and this particular font fits our requirement quite well.

Click on “Select this Font”:


Screenshot of Google Font page of Orbitron font


You will see the “Select this font” link once you visit the Google font link

A popover will appear at the bottom. Click on it. You will get two codes: the <link> code to copy into your HTML, and the font-family code to use in your CSS:


Screenshot of Google Font page of Orbitron font with the font selected


When you click the “Select this font” link a pop-up will be displayed with link and “font-family” code of that font

Copy the <link> code into your HTML file just above the line where you are including your stylesheet.

Now let’s add some details of Iron Man inside the desc div:

<div class="id-card-wrapper">
    <div class="id-card">
        <div class="profile-row">
            <div class="dp">
                <div class="dp-arc-outer"></div>
                <div class="dp-arc-inner"></div>
                <img src="img/iron-man-dp.jpg">
            </div>
            <div class="desc">
                <h1>Tony Stark</h1>
                <p>Strength: Ironman Suit</p>
                <p>Weakness: None</p>
                <p>Known as: Iron Man</p>
            </div>
        </div>
    </div>
</div>

In our CSS, we will use the font-family code from Google Fonts to set the font of “desc” div:

.profile-row .desc 
  font-family: 'Orbitron', sans-serif;
  color: #a4f3f2;

.profile-row .desc h1 
  margin: 0px;

Wait a sec, why are we setting the margin of h1 to 0?

All the heading elements (h1, h2, h3, h4, and h5) are displayed with some margin around it by the browsers. This is usually not a problem, but we don’t want the top and bottom gaps around the heading elements right now. That’s why we zeroed the margin for h1 element.

Let’s have a look at the output:

See the Pen Avengers ID Card – 4 by Kunal Sarkar (@supersarkar) on CodePen.

Oh no! What happened?

What’s happening is, the height of the dp div is increasing.

Normally, if the content in the desc div is of more height than the height of the dp div then nothing happens to the dp div. However, in flexbox layout, the height of the dp div will also increase along with the height of the desc div.

We don’t want the dp div to increase in height with the desc div, and we can do that by using [align-self](https://developer.mozilla.org/en-US/docs/Web/CSS/align-self) sub-property of flexbox:

.profile-row .dp 
  flex-basis: 33.3%;
  align-self: center;
  position: relative;
  margin: 24px;

See the Pen Avengers ID Card – 5 by Kunal Sarkar (@supersarkar) on CodePen.

The align-self: center makes the dp div to center keeping its height the same.

Adding Glow

Let’s add some glow.

But wait, CSS doesn’t have any glow property.

No problem, it does have the [text-shadow](https://developer.mozilla.org/en-US/docs/Web/CSS/text-shadow) property. If we give a bright color to the shadow, the shadow will look like it’s glowing:

.profile-row .desc 
  font-family: 'Orbitron', sans-serif;
  color: #d3f8f7;
  text-shadow: 0px 0px 4px #12a0a0;
  letter-spacing: 1px;

In the text-shadow property, the first value, 0px, is the x-offset, how much the shadow is away from text in the x-direction. The second value, 0px, is the y-offset, telling us how much the shadow is away from the text in the y-direction. The third value, 4px, is the amount of blur you want to give to the shadow. The fourth value, #12a0a0, is the color of the shadow.

Note, we also added a 1px space between the letters of text using the [letter-spacing](https://developer.mozilla.org/en-US/docs/Web/CSS/letter-spacing) property because the text was looking a bit congested.

Next, let’s add some shadow to the ID card and the image:

.id-card 
  flex-basis: 100%;
  max-width: 30em;
  border: 1px solid rgb(97, 245, 245);
  margin: auto;
  color: #fff;
  padding: 1em;
  background-color: #0D2C36;
  box-shadow: 0px 0px 3px 1px #12a0a0, inset 0px 0px 3px 1px #12a0a0;

.profile-row .dp img 
  max-width: 100%;
  border-radius: 50%;
  display: block;
  box-shadow: 0px 0px 4px 3px #12a0a0;

The text-shadow property gives shadow to the text, and the [box-shadow](https://developer.mozilla.org/en-US/docs/Web/CSS/box-shadow) property gives shadow to the elements.

The first three values for box-shadow are the same as text-shadow: x-offset, y-offset, and blur. The fourth value is how much you want the shadow to spread, and the fifth value is the color of the shadow.

Notice how we are giving two shadows, outer and inner, to the id-card div in a single line:

box-shadow: 0px 0px 3px 1px #12a0a0, inset 0px 0px 3px 1px #12a0a0;

The first five values create an outer shadow. Then the “inset” keyword specifies that the next five values are for inside shadow. We separate both with a ,.

See the Pen Avengers ID Card by Kunal Sarkar (@supersarkar) on CodePen.

The Avengers ID card is ready. Yay!

Wrapping Up

In this tutorial, we learned an effective way of making a full-page background, and centering elements with Flexbox and auto margins. We saw the basic usage of Flexbox and nested Flexboxes to make single dimension layouts.

If you want to dive deeper into Flexbox, check out “A Complete Guide to Flexbox” by Chris Coyier at CSS-Tricks. If you are more of a video learner, then you will enjoy the free 20 video course by Web Bos at Flexbox.io.

We also used CSS animations and the rotate transform to make animated arcs, however, we used a limited number of CSS properties and values. If you want to explore more about CSS animations then you will love this detailed MDN guide.

Finally, the glowing elements gave our ID card a unique sci-fi look. We used the “box-shadow” property to give the glow to our elements. Sometimes manually setting the values of the “box-shadow” property becomes cumbersome. Use CSSmatic’s Box Shadow CSS Generator to easily generate box shadows.

Smashing Editorial
(rb, ra, il)


Original post: 

Making Avengers ID Card In HTML And CSS

Thumbnail

Styling Empty Cells With Generated Content And CSS Grid Layout

A common Grid Layout gotcha is when a newcomer to the layout method wonders how to style a grid cell which doesn’t contain any content. In the current Level 1 specification, this isn’t possible since there is no way to target an empty Grid Cell or Grid Area and apply styling. This means that to apply styling, you need to insert an element.
In this article, I am going to take a look at how to use CSS Generated Content to achieve styling of empty cells without adding redundant empty elements and show some use cases where this technique makes sense.

Source:

Styling Empty Cells With Generated Content And CSS Grid Layout

Enter The Dragon (Drop): Accessible List Reordering

Over the years of being a web developer with a focus on accessibility, I have mostly dealt with widely-adopted, standardized UI components, well supported by assistive technologies (AT). For these types of widgets, there are concise ARIA authoring practices as well as great tools like axe-core that can be used to test web components for accessibility issues. Creating less common widgets, especially those that have no widely-adopted conventions for user interaction can be very tricky.

See the original article here:  

Enter The Dragon (Drop): Accessible List Reordering

What Science Can Teach Us About How to Create Viral Content

Think about the last thing you shared on the internet. Maybe it was an insightful video on the political turmoil in a far away country, or maybe it was a funny picture of a cat wearing a bow tie. Either way – you saw it, had an emotional reaction to it and decided to share it with others. But in the process of sharing the latest video, picture or article to your social media feeds – did you ever stop to think about why you shared it? What was your emotional response to the content? What about that response made…

The post What Science Can Teach Us About How to Create Viral Content appeared first on The Daily Egg.

Source:

What Science Can Teach Us About How to Create Viral Content

The Nine Principles Of Design Implementation

Recently, I was leading a training session for one of our clients on best practices for implementing designs using HTML and CSS. Part of our time included a discussion of processes such as style-guide-driven development, approaches such as OOCSS and SMACSS, and modular design. Near the end of the last day, someone asked, “But how will we know if we’ve done it right?”
At first, I was confused. I had just spent hours telling them everything they need to “do it right.

Continue reading: 

The Nine Principles Of Design Implementation

HTML APIs: What They Are And How To Design A Good One

As JavaScript developers, we often forget that not everyone has the same knowledge as us. It’s called the curse of knowledge: When we’re an expert on something, we cannot remember how confused we felt as newbies. We overestimate what people will find easy. Therefore, we think that requiring a bunch of JavaScript to initialize or configure the libraries we write is OK. Meanwhile, some of our users struggle to use them, frantically copying and pasting examples from the documentation, tweaking them at random until they work.

See original article: 

HTML APIs: What They Are And How To Design A Good One

Photoshop Etiquette For Responsive Web Design

It’s been almost five years since Photoshop Etiquette launched, which officially makes it a relic on the web. A lot can happen on the web in a few years, and these past five have illustrated that better than most.
In 2011, everyone was just getting their feet wet with responsive web design. The traditional comp-to-HTML workflow was only beginning to be critiqued, and since then, we’ve seen a myriad of alternatives.

View original post here:

Photoshop Etiquette For Responsive Web Design

Developers "Own" The Code, So Shouldn’t Designers "Own" The Experience?

We’ve all been there. You spent months gathering business requirements, working out complex user journeys, crafting precision interface elements and testing them on a representative sample of users, only to see a final product that bears little resemblance to the desired experience.
Maybe you should have been more forceful and insisted on an agile approach, despite your belief that the organization wasn’t ready? Perhaps you should have done a better job with your pattern portfolios, ensuring that the developers used your modular code library rather than creating five different variations of a carousel.

Link to original:

Developers "Own" The Code, So Shouldn’t Designers "Own" The Experience?

Web Development Reading List #128: Firefox 45, A Multi-Colored Font And Better Force-Pushing

Another week comes to an end, with new browser announcements, releases and cool new tools that you might want to check out. I make it short: Have fun reading this week’s reading list and enjoy your weekend!
Further Reading on SmashingMag: A User-Centered Approach To Web Design For Mobile Devices The Elements Of The Mobile User Experience A Guide To Designing Touch Keyboards (With Cheat Sheet)’“) Beyond The Button: Embracing The Gesture-Driven Interface News Firefox 45 is out and now re-evaluates responsive images in srcset on resize or viewport changes.

View the original here:  

Web Development Reading List #128: Firefox 45, A Multi-Colored Font And Better Force-Pushing