Salta al contingut principal

CSS3 Conditional Statements

In times gone by a web designer had only the properties and values in his head to style a website. Nowadays however, things are a little more complex, and they’re about to get even more so with the CSS Working Group’s conditional CSS statements.



This article is about new CSS which may not be supported in every browser! Be careful.

I say almost introductive because you might have heard of these new things called media queries. Media queries are a type of conditional statement where you can style a webpage based on the properties of a user’s computer. For example, one might say the following in their CSS stylesheet:



@media screen and (min-width: 1000px) {

/* CSS Goes here! */

}

The stuff you put in the curly brackets will only apply to screens with a width greater than 1000px. There are a bunch of other media queries regarding resolution, etc. I’m sure you’re quite familiar with them. What you may not know however is the CSS Conditional Statement Specification also talks about two other CSS conditional statements. Currently these two features are only supported in Firefox (6.0 for @document and 17.0 for @supports)


@supports



Suppose a particular brand of browser supports a feature, but another doesn’t. You then have a back up CSS script planned for browsers that do not support that particular feature. Well, @supports can help you with that! @supports checks to see if the property you call is supported in the browser.


So lets say (for some reason) you only want CSS to apply to a browser with the CSS flexible box model supported. You might do something like this:



@supports (display: flex) {
/* Put some CSS here */
}

The CSS in the curly brackets will only be enabled should the browser support the flex box. Then you can have other CSS which overrides that CSS should the browser not support the flex box, i.e.:



@supports (display: flex) {
/* Flexible box CSS goes here */
}

/* If flexbox isn't supported, backup CSS goes here */

Similar to media queries, you can check for multiple things using or and and.



@supports (display: flex) and (box-shadow: 0 0 10px rgba(0,0,0,0.1) {
/* If box shadows and the flex box are supported */
}
@supports ((display: flex) and (animation-duration: 1s)) or ((diplay: flex) and (transition-duration: 1s)) {
/* If flex box and animation duration are supported, or if flex box and transition duration are supported */
}

Negation


You can check if a browser doesn’t support a feature too using not(). For example, the CSS in the curly brackets below will only be applicable when flexbox isn’t supported:



@supports not(display: flex) {
/* Back up CSS goes here */
}

@document



@document styles CSS based on the page you are on. For example, it would be totally possible to do this to target a specific URL with CSS:



@document url('http://www.inserthtml.com/') {
/* CSS goes here */
}

Or you could apply it to everything in a particular folder:



@document url-prefix('http://www.inserthtml.com/css') {
/* CSS goes here */
}

The Benefits


Faster loading times


Presumably you can use this little trick to have a single unified header which selects which files to include based more on the user’s browser’s capabilities. For example, lets suppose you have some additional extras (box shadows, border-radius, etc), which are intended for newer browsers. When it comes to IE this can be a big problem because IE doesn’t support a lot of these features but you still have to load the CSS file. Using @supports you could reduce your primary CSS file and include the added extras as necessary in separate CSS files, thus improving page load times.




<link rel="stylesheet" type="text/css" href="style.css" />

<!-- Optional extras -->
<style>

@supports (box-shadow: 0 0 10px rgba(0,0,0,0.1)) {
@import url('box-shadow.css');
}

</style>

One Stylesheet for everything


Alternatively, you can have one stylesheet for everything since you can load the page specific and support specific CSS within these conditional statements. This is a good idea since the single CSS file will be stored in the user’s cache, so the page will load faster after the first visit.




@supports (display: flexbox) {
/* If supported, do this CSS */
}

/* Some regular CSS here */
div {
...
}

@document url('http://www.inserthtml.com/page.html') {
/* CSS for specific page */
}

@media print {
/* Media CSS */
}


Current Support



























FeatureChromeSafariFirefoxIEOpera
@documentNoneNone6.0NoneNone
@supportsNoneNone17.0NoneNone







via InsertHTML http://www.inserthtml.com/2012/09/css3-conditional-statements/?utm_source=feedburner&utm_medium=feed&utm_campaign=Feed%3A+inserthtml+%28InsertHTML%29

Comentaris

Entrades populars d'aquest blog

15 Tutoriales CSS3 para mejorar tus paginas web

15 Tutoriales CSS3 para mejorar tus paginas web : Les dejo una pequeña recopilación de tutoriales CSS3 que espero sean de utilidad para ustedes, intentamos hacer una recopilación bastante completa para crear impresionantes diseños web con CSS3 y aprovechar las bondades de CSS3 incluso para aplicar efectos, son un total de 15 tutoriales CSS3 gratis . Crear menu dropdown con CSS3 Crear breadcrumbs con estilo Transiciones de paginas con CSS3 Crear timeline con CSS3 y jQuery Reproductor de video con HTML5, CSS3 y jQuery Crear efecto acordion CSS3 Aplicar degradado a texto Crear texto en curva con CSS3 y jQuery Aplicar textura a texto con Magic Pill Crear slider de imagenes con CSS3 y jQuery Rotar texto con CSS3 Crear menu vertical con CSS3 Crear formulario con HTML5 y CSS3 Crear efecto de imagenes apiladas con CSS3 Aplicar estilos para imagenes con CSS3  

Averiguar la Salud del Disco Duro, con Crystal Disk Info [Windows]

Averiguar la Salud del Disco Duro, con Crystal Disk Info [Windows] : El actual “cuello de botella” en nuestras PCs; es decir, donde todo el rendimiento de nuestra PC llega a estancarse , es en el Disco Duro. Si bien los procesadores han evolucionado considerablemente en velocidad / rendimiento, el RAM no sólo es más económico, sino más veloz, y las tarjetas de video siguen innovando con cada generación, los discos duros han permanecido idénticos desde hace años, limitados por la física. Y es que un disco duro tradicional sólo tiene un máximo de velocidad con el que puede girar (medido en revoluciones por minuto, o RPM) que, a su vez, limita la velocidad de lectura y escritura. En pocas palabras, a pesar de que nuestras PCs pueden procesar información mucho más rápido que hace 5 años, los discos duros siguen leyendo (y escribiendo) esta información prácticamente a la misma velocidad. Esto ha cambiado con la llegada de los SSD, los Discos de Estado Sólo que no están limitados por la velo...

Cómo programar add-ons en XBMC: Un add-on más completo

Este tutorial forma parte de la serie Cómo programar un add-on de XBMC Estamos a mitad de camino de este tutorial, pero ya tienes el conocimiento necesario para hacer un add-on bastante completo. Espero que a estas alturas ya te hayas convencido de que es algo relativamente sencillo sin necesidad de saber demasiado de programación. Y ya sabes cómo obtener datos de una página HTML usando expresiones regulares, que es lo más difícil. Así que antes de entrar en la recta final vamos construir un add-on paso a paso desde cero, con el objetivo de afianzar lo que has aprendido en las entregas anteriores y de paso divertirte un poco. Te aconsejo que elijas un sitio web que te guste como fuente de vídeos, para mí he elegido hacer un add-on completo que permita ver los vídeos de Disney Junior tanto en la web oficial como en YouTube. No se trata de un add-on demasiado complejo, como podrás comprobar enseguida, pero no va a desmerecer en nada a cualquiera de los que puedes encontrar publicados en...