Skip to content

Instantly share code, notes, and snippets.

@emilbjorklund
Created April 24, 2012 16:03
Show Gist options
  • Save emilbjorklund/2481019 to your computer and use it in GitHub Desktop.
Save emilbjorklund/2481019 to your computer and use it in GitHub Desktop.
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
Copy link

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