Skip to content

Instantly share code, notes, and snippets.

@SimonPadbury
Last active June 23, 2018 06:38
Show Gist options
  • Save SimonPadbury/a3bd533d8a003cd7fae5385b0f799700 to your computer and use it in GitHub Desktop.
Save SimonPadbury/a3bd533d8a003cd7fae5385b0f799700 to your computer and use it in GitHub Desktop.
Container Query (max-width) JavaScript

Container Query (max-width)

This tiny JavaScript (no jQuery etc. required) looks for every data attribute data-max-width and records its value (that you set, in pixels). Example:

<div data-max-width="1000" class="my-container">
  ...
</div>

On page load and on viewport resize, a function is triggered that adds the CSS class .max-width if this DIV* is >= the data-max-width value – or else removes .max-width.

Now all you have to do is add some styles. Example:

.my-container {}

.max-width.my-container {}

*It doesn't have to be a DIV. It can be any element.

(function () {
"use strict";
/* eslint-env browser */
/* jshint browser: true */
// Document Ready
document.addEventListener("DOMContentLoaded", function () {
[].forEach.call(document.querySelectorAll('[data-max-width]'), function (el) {
var maxWidth = el.getAttribute('data-max-width');
function cqMaxWidth () {
var positionInfo = el.getBoundingClientRect(),
currentWidth = positionInfo.width;
if (currentWidth >= maxWidth) {
el.classList.add('max-width');
} else {
el.classList.remove('max-width');
}
}
cqMaxWidth();
window.addEventListener('resize', cqMaxWidth);
});
// End Document Ready
}, false);
}());
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment