- Use element queries effortlessly on any element or component.
- Use it in the form of the
{{element-query}}
modifier or the<ElementQuery as |EQ|>
component. - Apply styles that respond based on element's own width rather than viewport width.
- Do CSS transforations and template transformations.
Element queries are a technique to do responsive transformations based on element's own size rather than viewport size.
It lets you implement reusable responsive components β with encapsulated styles, decoupled from their parent context. Such components will realign their content depending on how much space is available to them.
For example, if you put a responsive component into a tight sidebar, it will align its content vertically. When the sidebar expands, the component will realign horizontally in order to efficiently use available space.
Here's a biased comparison table with competing addons (as of 2021.08):
ember-element-query | ember-fill-up | ember-container-query | |
---|---|---|---|
Octane | β | π« | β |
ResizeObserver | β | β | π« |
Offers a modifier | β | π« | π« |
Offers a component | β | β | β |
Actively maintained | β | π« | β |
API convenience | βββββ | ββββ | ββββ |
See detailed comparison with code samples.
- Demo
- API Docs
- Roadmap
- Rationale
- Concept of sizes
- How ember-element-query works
- Installation
- Usage
- Advanced usage
- Browser support
- Alternatives
- Comparison
- Defining custom rules rules, using template and CSS transformations
- Using default rule definitions
- Customizing element tag while doing template transformations
- Customizing element tag while doing pure CSS transformations
- Using directly on images and other void elements
- Using both width and height in a rule for template transformation
- Comparison
- Contributing
- License
- Credit
https://lolmaus.github.io/ember-element-query/
This addon's demo is borrowed from ember-container-query per @ijlee2's generous permission.
https://lolmaus.github.io/ember-element-query/api/
This addon is in active development complete! π
-
{{element-query}}
modifier- Exists
- Sets up a
ResizeObserver
- Calls the
onResize
callback with params - Applies attributes to elements
- Accepts
sizes
- Accepts
sizesHeight
- Accepts
sizesRatio
- Accepts
prefix
- Updates on arugments change
- Add fool-proof exceptions
- Disabling
- Applying a general
[eq]
attribute
-
<ElementQuery>
component- Exists
- Applies attributes to itself
- Calls the
onResize
callback with params - Yields block params
- Accepts
sizes
- Accepts
sizesHeight
- Accepts
sizesRatio
- Accepts
prefix
- Accepts
tagName
- Disabling
- Expose types
- CI
- npm package
- Documentation
- Concept
- Feature description
- Usage
- Browser support
- Comparison with alternatives
- TypeDoc API documentation
- Document
- Set up auto deployment
- Demo app
CSS media queries have a few disadvantages:
- They account for scrollbar width. On OSes with a scrollbar such as Windows and Linux, available document width is some 15px smaller than the one detected by a media query. Resulting styles are slightly inconsistent across OSes.
- They are designed for creating responsive layouts, whereas making responsive components is unreasonably hard:
- If your responsive component appears in different contexts, you have to define media queries separately for each context and make sure they don't overlap.
- If you want to make your responsive component reusable, you can't apply responsive styles directly to it because you don't know all the contexts it might be used in. Instead, you have to offer the styles as preprocessor mixins or CSS snippets, for the consuming app developer to apply them by hand in every context.
- Responsive components put into dynamic contexts (such as collapsible sidebars, grids, other responsive components, etc) require lots of media queries, which involve unreasonably complicated math. Check out this old demo for a rationale.
All those problems wouldn't exist if we were able to apply styles conditionally based on element's own width:
/* Hypothetical sample. I wish these were possible, but alas! */
/* When .my-menu is <= 499px, apply margin-bottom to .my-menu--item */
.my-menu:max-width(499px) .my-menu--item {
margin-bottom: 10px;
}
/* When .my-menu is >= 500px, apply flex to it */
.my-menu:min-width(500px) {
display: flex;
}
/* When .my-menu is >= 500px, apply margin-right to .my-menu--item */
.my-menu:min-width(500px) .my-menu--item {
margin-right: 10px;
}
Unfortunately, CSS is not aware of element's current width, so pseudoselectors like :min-width(500px)
are impossible... unless you use a tool like ember-element-query
.
ember-element-query
operates with sizes. "Sizes" are like T-shirt sizes, except they indicate element width.
The default sizes scale is:
Breakpoints: 0 200px 400px 600px 800px 1000px 1200px 1400px
βββββββββββΌββββββββββΌββββββββββΌββββββββββΌββββββββββΌββββββββββΌββββββββββΌβββββββββ>
Sizes: Β· xxs Β· xs Β· s Β· m Β· l Β· xl Β· xxl Β· xxxl
The left limit of each size range is inclusive, the right limit is non-inclusive.
For example, an element is considered to be of size m
when its width is >= 600px
and < 800px
.
Here's an explicit sizes chart:
Breakpoints: 0 200px 400px 600px 800px 1000px 1200px 1400px
βββββββββββΌββββββββββΌββββββββββΌββββββββββΌββββββββββΌββββββββββΌββββββββββΌβββββββββ>
Sizes: Β· xxs Β· xs Β· s Β· m Β· l Β· xl Β· xxl Β· xxxl
Β· Β· Β· Β· Β· Β· Β· Β·
xxs β Β· Β· Β· Β· Β· Β· Β·
0β199 ββββββββββ€Β· Β· Β· Β· Β· Β· Β·
Β· Β· Β· Β· Β· Β· Β· Β·
xs βββββββββββ€ Β· Β· Β· Β· Β· Β·
200β399 ββββββββββββββββββββ€Β· Β· Β· Β· Β· Β·
Β· Β· Β· Β· Β· Β· Β· Β·
s βββββββββββββββββββββ€ Β· Β· Β· Β· Β·
400β599 ββββββββββββββββββββββββββββββ€Β· Β· Β· Β· Β·
Β· Β· Β· Β· Β· Β· Β· Β·
m βββββββββββββββββββββββββββββββ€ Β· Β· Β· Β·
600β799 ββββββββββββββββββββββββββββββββββββββββ€Β· Β· Β· Β·
Β· Β· Β· Β· Β· Β· Β· Β·
l βββββββββββββββββββββββββββββββββββββββββ€ Β· Β· Β·
800β999 ββββββββββββββββββββββββββββββββββββββββββββββββββ€Β· Β· Β·
Β· Β· Β· Β· Β· Β· Β· Β·
xl βββββββββββββββββββββββββββββββββββββββββββββββββββ€ Β· Β·
1000β1199 ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ€Β· Β·
Β· Β· Β· Β· Β· Β· Β· Β·
xxl βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ€ Β·
1200β1399 ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ€Β·
Β· Β· Β· Β· Β· Β· Β· Β·
xxxl βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ€
1400+ βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ>
ember-element-query
applies HTML attributes to an element indicating its current size.
There are three types of attributes, all of them are applied at once:
-
at-<size>
attribute is applied with element's current size.For example, an element with width of
764px
will receive anat-m
attribute. -
from-<size>
attributes are applied with element's current size and all smaller sizes.For example, an element with width of
764px
will receive attributesfrom-xxs
,from-xs
,from-s
andfrom-m
. -
to-<size>
attributes are applied with element's current size and all larger sizes.For example, an element with width of
764px
will receive attributesto-m
,to-l
,to-xxl
andto-xxxl
.
Don't feel confused! This is very simple:
- When you want say "when my element is of size M", use the
at-m
attribute. - When you want say "when my element is of size M or larger", use the
from-m
attribute. - When you want say "when my element is of size M or small", use the
to-m
attribute.
In order to do responsive CSS transformations, use attributes like this:
.foo[at-xxs] {
/* These styles when be applied when the element has exactly the size of `xxs`, namely 0β199 px. */
}
.foo[from-xs] {
/* These styles when be applied when the element has the size of `xxs` or larger, namely 200+ px. */
}
.foo[to-xl] {
/* These styles when be applied when the element has the size of `xl` or smaller, namely 0β1199 px. */
}
.foo[from-s][to-l] {
/* These styles when be applied when the element has the size between `s` and `l` inclusively, namely 400β999 px. */
}
Responsive template transformations are also possible, see below.
Note that some attribute usages don't make much sense:
- The smallest
from-
and the largestto-
attribute are applied at all times, thus.foo[from-xxs]
and.foo[to-xxxl]
selectors are both equivalent to simply.foo
. .foo[to-xxs]
is equivalent to.foo[at-xxs]
, and.foo[from-xxxl]
is equivalent to.foo[at-xxxl]
..foo[from-m][to-m]
is equivalent to.foo[at-m]
.
Attribute selectors in CSS should only be used in conjunction with semantic selectors.
The following usage will mess up you website/app:
/* Never do this! */
[at-m] {
float: left;
}
/* Still quite bad */
aside[at-m] {
float: left;
}
/* OK */
.my-side-block[at-m] {
float: left;
}
Use ember-cli
to install the addon as usual:
ember i ember-element-query
This addon does not do anything on install, so it can alternatively be installed with npm:
npm i -D ember-element-query
...or Yarn:
yarn add -D ember-element-query
Using the modifier is preferred if you only do CSS transformations, which is recommended according to the Responsiv Web Design doctrine.
Simply apply the {{element-query}}
modifier to any element or angle bracket component like this:
As a result, element query attributes will be applied to the element. The result could look like this:
The component is useful when you need to do template transformations.
If you want to render chunks of template conditionally, use this syntax:
The first yield argument EQ
is an object with current element query attributes. Keys are attribute names and values are true
. Non-matching attributes are undefined. Thus, {{#if EQ.from-m}}
renders only when the element is of size m
or larger.
The second argument EQInfo
is the same object that is passed to the onResize callback described below.
You can pass a callback to the onResize
argument and it will be called whenever the element resizes:
@action
reportResize(eqInfo) {
eqInfo.element // => current element
eqInfo.width // => current element's width in px (number)
eqInfo.height // => current element's height in px (number)
eqInfo.ratio // => current element's aspect ratio (width/height, number)
eqInfo.size // => current element's width size name (string or undefined)
eqInfo.sizeHeight // => current element's height size name (string or undefined)
eqInfo.sizeRatio // => current element's aspect ratio size name (string or undefined)
eqInfo.prefix // => current prefix (string or undefined)
eqInfo.attributes // => matching element query attributes in array form: ['from-xxs', 'from-xs', ...]
eqInfo.attributesRecord // => matching element query attributes in object form: {'from-xxs': true, 'from-xs': true, ...}
// non-matching attributes are not defined on the object
}
Your tailored visual designs might require component switching layouts at specific breakpoints, different from this addon's defaults.
You can override the defaults with the sizes
argument. It receives a plain object where keys are breakpoint names and arguments are numbers representing width.
β One of the numbers must be 0, otherwise the addon will crash your app.
The above example defines sizes like this:
small
: 0β349 px,medium
: 350β699 px,large
: 700+ px.
When the element has the width of 421px
, it will receive attributes at-medium
, from-medium
, to-medium
, from-small
and to-large
. (Confused? See above.)
By default, only attributes for horizontal sizes are applied to your element.
If you want to use attributes for vertical sizes, set sizesHeight
to true
:
Enabling heightSizes
will cause two sets of attributes to be applied: width and height. Attributes representing width sizes will be the same as usual. Attributes representing height sizes will be postfixed with -height
: xxs-height
, xl-height
, etc.
This lets you apply CSS like this:
.foo[to-s][from-xl-height] {
/* I am thin and tall */
}
You can customize height sizes by passing a hash to @sizesHeight
. Make sure that height size names are different from width sizes!
Of course, you can customize both sizes
and sizesHeight
at the same time if you need.
By default, only attributes for horizontal sizes are applied to your element.
If you want to use attributes for aspect ratio sizes, set sizesRatio
to true
:
By default, the following definition of aspect ratio sizes is used:
{
'very-tall': 0,
'tall': 0.5,
'squarish': 0.8,
'wide': 1.2,
'very-wide': 1.5,
}
Note that while width and height use whole number of CSS pixels, ratios use fractions. For example, an element with the size of 1920Γ1080
will have an aspect ratio of 1.777...
, which correpsonds to the very-wide
ratio size.
You can customize ratio sizes by passing a hash to @sizesRatio
. Make sure that aspect ratio size names are different from width and height sizes!
* Mind that comparison of fractional numbers is not absolutely accurate in JavaScript. Aspect ratio sizes are supposed to represent ranges of aspect ratios, not individual aspect ratios. Aiming at a specicific aspect ratio (like in example above) may be inconsistent.
By default, default width attributes are applied to your element unless the sizes
is overridden.
If you want no width attributes to be applied, pass a falsy value into sizes
.
Using height without width:
Using no attributes at all:
The above will make it impossible to apply CSS or HTML transformations based on sizes. But the following features will still work:
- The
onResize
callback will be called with an object containing current width, height and aspect ratio of the element. - The
<ElementQuery>
component will yield an object containing current width, height and aspect ratio of the element. - The
eq
attribute will still be applied to the element. This hapens when the element query triggers for the first time.
Use the prefix
argument to adjust attribute prefix:
This will result in attributes like data-foo-at-xl
, data-foo-from-m
, etc.
One use case for this is to apply new styles based on new breakpoints without breaking (and refactoring) existing styles.
You can use both width and height element queries on the same element like this:
or
β The {{element-query}}
modifier adds and removes attributes aggressively and will interfere with other modifiers/libraries manipulating same attributes. It is your duty to ensure there is no conflict in attribute names. Adjust sizes
, sizesHeight
and prefix
arguments to avoid conflicts.
Pass a truthy value into isDisabled
to disable element query functionality:
β This property is intended for debugging purposes or disabling element queries entirely. If you change isDisabled
to true
dynamically, element query attributes will freeze in their current state. There is no cleanup.
The <ElementQuery>
component accepts a @tagName
argument that allows tweaking the component's root tag:
This wouuld result in the followingg HTML rendered (element query tags not shown):
Use the debounce
argument to set a limit to how frequently attributes recalculate and the onResize
callback is called while the window is being continuously resized.
It accepts a number of milliseconds and defaults to 100
. This means that the refresh will be happening at a rate of 10 times per second (1000 / 100 = 10).
This example with refresh once per second:
This addon uses window.requestAnimationFrame. Even if you set debounce
to 0
, the refresh rate will still be limited to either 60 or to the refresh rate of the screen.
It is not recommended to use a low refresh rate due to possible perormance issues. For example, if you do this:
@service cdn;
@action updateSrc({element, width, height}) {
element.src = this.cdn.getImageSrcForSize({width, height});
}
...then playing with window size for several seconds will cause hundreds or thousands of src
updates to be queued, which would cause the image to flicker.
β When navigating between routes, there may be a flash of unstyled content: a very short moment when the component is rendered, but its element queries are not applied yet. This happens because ember-element-query
addon needs the component to be rendered in order to measure its size, before responsive styles can be applied.
Consider this SCSS. Here we have two layouts: horizontal and vertical.
.MyComponent {
// This layout will be applied when the element is known to be small.
&[to-m] {
// Vertical layout. Children should have margins between them.
> *:not(:last-child) {
margin-bottom: 20px;
}
}
// This layout is applied when the element is known to be large.
&[from-l] {
// Horizontal layout. Children should be positioned in a row.
margin-bottom: 20px;
}
}
During the flash of unstyled content, neither layout is applied because ember-element-query
hasn't yet applied its attributes.
This is suboptimal. Instead, you want one of the layouts to be the default one: applied when element query attributes are unavailable.
For this use case, when the element's size is first measured, ember-element-query
applies the eq
attribute to the element and keeps it forever. Thus, the :not([eq])
selector matches the element only while element queries have not yet being applied.
In order to make one of the layouts a default, add :not([eq])
to its selectors:
.MyComponent {
// This layout will be applied when the element is known to be small or when its size is unknown.
&:not([eq]), &[to-m] {
// Vertical layout. Children should have margins between them.
> *:not(:last-child) {
margin-bottom: 20px;
}
}
// This layout is applied when the element is known to be large.
&[from-l] {
// Horizontal layout. Children should be positioned in a row.
margin-bottom: 20px;
}
}
This would remove the flash of unstyled content at least for some screen sizes.
Unfortunately, FastBoot does not have information about user's screen size. When a user vistis a FastBoot-driven website, they initially see a page without any ember-element-query
attributes. When FastBoot rehydrates, element queries kick in. As a result, page layout may suddenly change after the user has already started reading and scrolling, causing frustration.
One workaround is to use ember-useragent. Its isMobile
, isTablet
and isDesktop
boolean properties let you apply some defaults. The result is very crude, heuristical β but that's better than nothing.
Since reusable components can be used in different contexts, it is recommended that you apply the fallback on parent level.
Responsive component:
.my-component { /* */}
.my-component[from-medium] { /* */ }
.my-component[from-large] { /* */ }
Parent:
Unfortunately, this requires the parent to know which attributes are used in component's CSS, since providing all possible attributes would be quite tedious, especially for default sizes, which are numerous.
IE is not supported because ember-element-query
uses modern ECMAScript APIs.
ember-element-query
is based on the ResizeObserver which is also not supported by IE.
As of 2020-06, ResizeObserver
supports the following major browsers:
- Chrome: 64+ (since 2018-01-23),
- Firefox: 69+ (since 2019-09-02, desktop only),
- Safari: 13.1+ desktop, 13.4+ iOS (since 2020-03-24).
See caniuse.com for detailed stats.
β Note that old iOS devices do not have ResizeObserver
support, so you might want to use a polyfill. iOS Safari is the new IE. π¬
There are a few other Ember addons implementing element queries, such as:
ember-element-query
was implemented to offer a simpler API at the cost of being opinionated.
Other addons are full-fledged element query addons that aren't as much opinionated. Their approach is defining rules on element query components. For example, if you want your component to respond to 0β350px
, 350px+
, 350pxβ699px
and 700px+
β you will need to define four rules on the component. An unexpected challenge is to come up with meaningful names for each range.
Every time you need another rule, you need to add it on the component before you're able to use it in CSS.
With ember-element-query
, you only need to define breakpoints. The example above uses only two breakpoints: 350px
and 700px
β and all combinations of rules become available automatically via HTML attributes.
π‘ ember-fill-up
and ember-container-query
and ember-element-query
are all full-featured element query addons. ember-element-query
's goal is to provide a simpler API, making it more convenient to use. It encourages using pure CSS transformations, accoridng to the Responsive Web Design paradigm, though template transformations are also possible and convenient.
As of 2021.08.
Given breakpoints 350, 700 and 1050:
-
ember-fill-up
:.my-component[fill-up-small] {} .my-component[fill-up-medium] {} .my-component[fill-up-large] {} .my-component[fill-up-extraLarge] {} .my-component[fill-up-mediumToLarge] {} .my-component[fill-up-largeAndBigger] {} .my-component[fill-up-mediumAndSmaller] {} .my-component[fill-up-largeAndSmaller] {} .my-component[fill-up-mediumToLarge] {}
π Note how you need to repeat same breakpoints several times in rule definitions. In order to avoid multiple sources of truth, you could wrap component invocation with
{{let}}
, but that increases the boilerplate. -
ember-container-query
:.my-component[data-container-query-small] {} .my-component[data-container-query-medium] {} .my-component[data-container-query-large] {} .my-component[data-container-query-extraLarge] {} .my-component[data-container-query-mediumAndBigger] {} .my-component[data-container-query-largeAndBigger] {} .my-component[data-container-query-mediumAndSmaller] {} .my-component[data-container-query-largeAndSmaller] {} .my-component[data-container-query-mediumToLarge] {}
π Note how you need to manually account for Β±1 error in rule definitions.
-
ember-element-query
:.my-component[at-small] {} .my-component[at-medium] {} .my-component[at-large] {} .my-component[at-extraLarge] {} .my-component[from-medium] {} .my-component[from-large] {} .my-component[to-medium] {} .my-component[to-large] {} .my-component[from-medium][to-large] {}
π Note how much shorter the usage is, both in rule definitions and rule applications.
-
ember-fill-up
:Does not provide any defaults.
-
ember-container-query
:Does not provide any defaults.
-
ember-element-query
:Provides reasonable defaults.
Those defaults can be used as a common design language, and all components in your app can be using them, reducing the boilerplate to:
or
-
ember-fill-up
:Not supported. Responsive componetns are limited to
<div>
. -
ember-container-query
:Uses ember-element-helper as a polyfill for RFC 389 (tracking):
-
ember-element-query
:Uses ember-element-helper as a polyfill for RFC 389 (tracking):
-
ember-fill-up
:Not supported. Responsive componetns are limited to
<div>
. -
ember-container-query
:Uses ember-element-helper as a polyfill for RFC 389 (tracking):
-
ember-element-query
:Naturally:
-
ember-fill-up
:Not supported.
Workaround with two wrapper elements:
.wrapper1[fill-up-small] { opacity: 0.5; } .wrapper1[fill-up-large] { transform: rotate(5); } .wrapper2 { position: relative; padding-top: 56.25%; /* The ratio of the image must be known. Alternatively, the image can be cropped with `object-fit: cover` to arbitrary aspect ratio.*/ } .wrapper2 .image { position: absolute; top: 0; left: 0; width: 100%; height: 100%; }
-
ember-container-query
:Uses ember-element-helper as a polyfill for RFC 389 (tracking):
-
ember-element-query
:
-
ember-fill-up
: -
ember-container-query
: -
ember-element-query
:When usign default sizes, this gets even shorter:
git clone <repository-url>
cd ember-element-query
yarn
yarn lint:hbs
β only templatesyarn lint:ts
β only TypeScript compiler (tsc)yarn lint:eslint
β only ESLint (including Prettier andtypescript-eslint
)yarn lint
β everything
ember test
β Runs the test suite on the current Ember versionember test --server
β Runs the test suite in "watch mode"ember try:each
β Runs the test suite against multiple Ember versions
ember serve
- Visit the dummy application at http://localhost:4200.
For more information on using ember-cli, visit https://ember-cli.com/.
This project is licensed under the MIT License.
Implemented by Andrey Mikhaylov (lolmaus) and contributors.
Thanks to Chad Carbert (@chadian) and Isaac Lee (@ijlee2) for feedback, ideas, brainstorming and criticism.
This addon's demo is borrowed from ember-container-query per @ijlee2's generous permission.
Sponsored in part by @kaliber5, https://kaliber5.de.