Element Queries

It's been done by others before but I wanted to roll my own. Mine uses JSON data to specify the min/max-widths.

EDIT: Updated with ems, rems, % and vw - use them the same as you would with px.

What and why?

Elements respond to their own width and not the screen width. This means they can adapt to where ever they are placed in a layout.

Works with jQuery or Zepto and is ~460b when minified, ~280b when gzipped.

Examples

Change with the window width and see how the following adapt to their own size.

I won't respond thank you very much!
This should respond to it's own width
I am half
I am quarter
Me too!

%, em, rem and vw supported

Ems
Rems
Percent
vw ViewWidth

How?

Include jQuery/Zepto and the js and then add a data attribute to the element in question and defind any min-width and max-width.

 data-eq='{"min-width":[ "300px", "600px", "900px" ], "max-width":["600px", "1024px"]}'

CSS needs to have the relevent rules in to match the data attributes.

.element[min-width~="300px"] { ... whatever ... }
.element[max-width~="1024px"] { ... yeah! ... }

Advantages

Elements respond to their own width and not the page width. If used in conjunction with a component library ( like: http://rizzo.lonelyplanet.com/ ) then all data attributes can be managed easily. Without js the code defaults to the normal view so a fall back could be designed.

Disadvantages

Needs jQuery or Zepto to work and elements need to be marked up with the data attribute to work. If lots of elements are using it then it could be quite slow to rerender the page?!

Technical

This works by testing any elements with the data-eq attribute when the page loads and whenever the window is resized. If the element is bigger than a min-width data attribute or smaller than a max-width attribute the min and max width attributes are updated on the element so that the css rules can come into play.