Create a gist now

Instantly share code, notes, and snippets.

What would you like to do?
Width detection via sneaky CSS rules
<!DOCTYPE html>
<!--[if IE 8]> <html lang="sv-SE" class="no-js ie8"> <![endif]-->
<!--[if gt IE 8]><!--> <html lang="sv-SE" class="no-js"> <!--<![endif]-->
<head>
<meta charset="UTF-8">
<title>Breakpoint detection test</title>
<style type="text/css" media="screen">
@media screen and (min-width: 320px) {
#page:after {
content: 'smallest'; /* represent the current width-bracket */
display: none; /* hide ALL THE THINGS */
}
}
@media screen and (min-width: 480px) {
#page:after {
content: 'small'; /* represent the current width-bracket */
}
}
@media screen and (min-width: 600px) {
#page:after {
content: 'large'; /* represent the current width-bracket */
}
}
@media screen and (min-width: 768px) {
#page:after {
content: 'largest'; /* represent the current width-bracket */
}
}
</style>
</head>
<body>
<div id="page">
<h1>Reload at different viewport widths to trigger script.</h1>
</div>
<script type="text/javascript" charset="utf-8">
(function(win){
var doc=win.document,
el,
pseudo;
if (win.getComputedStyle && doc.querySelector) {
el = doc.querySelector('#page');
pseudo = win.getComputedStyle(el, ':after').getPropertyValue('content');
if (pseudo) {
alert(pseudo);
}
}
})(this);
</script>
</body>
</html>

kaplan commented Mar 4, 2014

This is really neat. I landed here from Jeremy Keith's Conditional CSS, but it looks like my latest version of Chrome ignores getComputedStyle(el, ':after').getPropertyValue('content'); when the display is none. It looks like it's a Chrome bug? https://code.google.com/p/chromium/issues/detail?id=236603

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment