Skip to content
tinytip

Latest tips / 10

Style Angular Components based on their context

October 9, 2021
#angular #css

The Angular :host-context() selector allows you to style your component based on some conditions outside the component - for example based on a class set on the body element - without the need to set view encapsulation to none.

The selector will look for a matching element in any ancestor of your component up to the document root.

:host-context(.dark-theme) .my-component {
/* Styles are applied when there is a
"dark-theme" class on any ancestor */

}

This is not limited to CSS class selectors but works with any valid CSS selector.

:host-context([theme="dark"]) .my-component {
/* Styles are applied when there is an ancestor
that has an attribute theme="dark" */

}

The CSS list-style property affects screen readers

October 9, 2021
#html #a11y
Credits: Scott O'Hara

If you have a ul element in your HTML and you set list-style: none via CSS (via inline styles, a style tag or an external stylesheet), your list will not be announced as a list anymore with VoiceOver + Safari on macOS.

<!-- VoiceOver + Safari will not announce this as a list -->
<ul style="list-style:none">
<li>...</li>
<li>...</li>
<li>...</li>
</ul>

Add the role attribute to the ul element to fix this behavior.

<!-- VoiceOver + Safari will now announce the list -->
<ul role="list" style="list-style:none">
<li>...</li>
<li>...</li>
<li>...</li>
</ul>

Alpine.js accepts a custom prefix for directives

September 21, 2021
#alpinejs

Alpine.js uses the x- prefix for directives by default (e.g. x-if). This prefix can be customized using Alpine.prefix().

Alpine.prefix("xyz-"); // Define your custom prefix
Alpine.start();
<!-- Use your custom prefix for all directives -->
<template xyz-if="user">
<a xyz-bind:href="user.profileUrl" xyz-text="user.name"></a>
</template>

This can be useful to prevent clashes when integrating Alpine into existing apps / markup or to get valid HTML markup that passes the W3C validator by using data-x- as prefix.

CSS has a turn unit to rotate elements

September 18, 2021
#css

The rotate function of the CSS transform property supports the turn unit. This can be used as an alternative to deg. 360 degrees correspond to 1 turn.

.element {
/* Instead of degrees ... */
transform: rotate(90deg);

/* ... you can use turn */
transform: rotate(0.25turn);
}

Let's see it in action:

Demo of rotated elements in CSS

Create an array with the map function of Array.from

September 4, 2021
#javascript #array

The Array.from function has a second parameter that lets you map each item to a new value.

The first argument of the map function is the current value or undefined if you don't have an existing list (as in the example below). The second argument is the index.

const items = Array.from({ length: 5 }, (value, idx) => idx + 1);
console.log(items); // [1, 2, 3, 4, 5]