7 Principios para mantener las Css limpias y optimizadas

1. Use Shorthand

If you’re not already writing in shorthand, you’re late to the party. But fortunately, this party never ends. Using shorthand properties is the single easiest practice you can do to cut down your code (and coding time). There’s no better time than the present to start this efficient coding practice, or to review it.

Margin, border, padding, background, font, list-style, and even outline are all properties that allow shorthand (and that’s not even an extensive list!).

CSS Shorthand means that instead of using different declarations for related properties…

view plaincopy to clipboardprint?

  1. p { margin-top10px;  
  2.     margin-right20px;  
  3.     margin-bottom:  30px;  
  4.     margin-left40px; }  
Array

… you may use shorthand properties to combine those values like so:

view plaincopy to clipboardprint?

  1. p { margin10px 20px 30px 40px; }  
Array

By specifying a different number of values, browsers would interpret the rules in a specified manner, illustrated in the diagram below.

Illustration of how shorthand declarations are interpreted depending on how many values are specified for a property
Illustration of how shorthand declarations are interpreted depending on how many values are specified for a property. This order also applies to padding and border-width among other properties.

Font is another helpful shorthand property that helps save some room and keystrokes.

Illustration of font shorthand examples
Examples of the font shorthand property. Note: leaving some values unspecified will mean that those properties will reset to thier initial values.

Those are just two examples of shorthand, but by no means should be considered a comprehensive guide. Even if you are familiar with the rules above, be sure to look at the articles mentioned below for more helpful reminders of those powerful properties that help keep your code succinct. Because of the number of lines and characters saved, going from a previous version of a CSS file which used no shorthand properties to one that makes full use of shorthand can have dramatic effect on file size.

See CSS Shorthand Guide (dustindiaz.com) and Efficient CSS with shorthand properties (456bereastreet.com) for more information about shorthand properties.

2. Axe the Hacks

Jon Hick's blog hicksdesign.co.uk/journal makes use of conditional comments
Jon Hick’s blog hicksdesign.co.uk/journal makes use of conditional comments

Hacks against dead browsers are safe, but hacks against the living aren’t. None of them. Ever.

Keep CSS Simple - Peter-Paul Koch (digitial-web.com)

If you’re like me, those words from Peter-Paul Koch’s nearly 5-year-old article may make you feel a little embarrased. After all, who hasn’t served hacks to Internet Explorer 6 and even Internet Explorer 7? As bad as we may want IE6 to lay six pixels under, the truth is it’s far from dead.

But now we know that using conditional comments to serve hacks correctional declarations for IE6 and IE7 is an accepted practice, even recommended by the Microsoft IE development team. Using conditional comments to serve IE-specific CSS rules has the added benefit of serving a cleaner, and therefore smaller, default CSS file to more standards-compliant browsers, while only those browsers that need the hackery daiquri (i.e. IE) will download the additional page weight.

Here’s how to use conditional comments to serve styles only to Internet Explorer 6:

view plaincopy to clipboardprint?

  1. <!–[if IE 6]>  
  2.     <link rel=“stylesheet” type=“text/css” href=“ie6.css”>  
  3. <![endif]–>  
Array

For IE7, you can use the above and substitute “6″ for “7″.

Alternatively, if there is hack-less way of getting the desired result using CSS, with all other things being equal, go for it! The less hacks you have to write, the simpler and lighter the code.

3. Use whitespace wisely

Whitespace, including spaces, tabs, and extra line breaks, is important for readability for CSS code. However, whitespace does add, however miniscule it may be, to page weight. Every space, line-break, and tab you can eliminate is like having one less character.

But this is one area where I would not encourage you to skimp just to get a smaller file. It’s still important that you write in a way that is readable to you (and hopefully to others), and if that includes using whitespace for formatting, so be it. After all, if you can’t read it, you’re going to have a hard time applying the other principles mentioned in this article. Just be aware of the fact that whitespace is like air - you might not be able to see it, but it does weigh something.

The figure below shows two different extremes in formatting style, with much whitespace, and the other with very little. I happen to favor the single-line formatting option without tabs, as I can scan the selectors a little easier, and I develop using the full width of my wide-screen monitor. But that’s just me. You may like your selectors to appear nested, and your declarations on each line.

Illustration of two extremes in CSS formatting, one with lots of whitespace, one with little whitespace
Illustration of two extremes in CSS formatting: lots of whitespace vs. very little whitespace

Using whitespace effectively is great, and a recommended practice for easy-to-manage code, but be aware that the less whitespace you have, the smaller the file. Even if you choose work with whitespace with your working file, you can choose to remove it for the production version of your CSS file, so your files stay skinny where it really counts.

4. Prune frameworks and resets

Nathan Smith's 960 Grid System uses a reset
Nathan Smith’s 960 Grid System CSS framework uses a reset rule.

If you’ve chosen to use a CSS framework (including ones you’ve written yourself), take the time to review the documentation as well as every line of the CSS file. You may find that the framework includes some rules that you don’t care to use for your current project, and they can be weeded out. Also, you may find that the framework includes a more elegant and concise way of achieving a presentational detail than what you normally use, and knowing about them can help prevent you duplicating rule sets unintentionally.

This goes for resets as well. YUI Grid CSS uses a reset, and Eric Meyer’s Reset is also very popular. Resets are great to use because they help to neutralize a browser’s default style. But if you know the nature of the site you are building, you may find some declarations that you know you’ll never need. <pre> and <code> will likely go unused on my Aunt Martha’s recipe blog. A design portfolio probably won’t ever use <sub>, <dfn>, <var>, etc. So ditch what you don’t need. It’s not only ok, it’s encouraged, even by Eric Meyer:

As I say on the reset page, those styles aren’t supposed to be left alone by anyone. They’re a starting point.

Crafting Ourselves - Eric Meyer (meyerweb.com)

Using a framework and/or a reset set of rules can help keep your work optimized, but they should not be accepted in their default state. Considering each declaration and cutting back on unneccessary ones can further help you keep your CSS files lean and readable.

5. Future-proof your CSS

Doug Bowman's stopdesign.com CSS reveals specially crafted selectors used for layout
Doug Bowman’s stopdesign.com CSS reveals specially crafted selectors used for layout.

Another way to optimize your code is to separate layout-specific declarations from the rest of your rules. I’ve heard options of separating typography and colors from layout-specific rules in the CSS file. I’ve never been fond of this practice, as I don’t care to repeat selectors just because I have different types of declarations to associate with them.

However, I’m warming up to the idea of separating layout styles from the rest of the styles, and giving layout it’s own file, or at least it’s own section. This is also advocated in Andy Clarke’s Transcending CSS. Within the book, Clarke reminds us of the following:

Full CSS layouts have always been a compromise. The current CSS specifications were never designed to create the visually rich and complex interface layouts that modern Web demands. The current methods — floats and positioning — were never intended as layout tools.

Transcending CSS - Andy Clarke.

One way of interpreting this is that floats and positions to establish sidebars and columns are, well, layout hacks. And though we really don’t have an alternative, we hopefully will once a layout standard is agreed upon and browsers start supporting them. When that happens, it should be easy to swap out those hacked up box-model properties for ones intended for layout. Though it will be a while before new layout modules are here, using the right properties to handle layout instead of compensating for the quirks of our current limited set of properties will most certainly help condense page weight.

6. Document your work

David Shea's markup guide at mezzoblue.com
David Shea’s markup guide illustrates the proper usage for HTML tags and how those are represented on his site, mezzoblue.com. Even sites without dynamic HTML can have this simple and effective guide (using its own CSS file, of course!) as a starting point of documentation.

For a team of designers, it is extremely important to communicate regularly so that markup and style rules are created in a consistent way, and also to create site standards. For example, if someone comes up with way to markup a tab interface for the site, documentation will keep others from duplicating that effort, preventing code bloat in the HTML and CSS.

Documentation, including markup guides and style sheet guides, is not just for group efforts — they are just as important for a one-man design team. After all, a year after working on other things, revisiting one of your own projects can feel quite foreign. Your future self might appreciate reminder of how your CSS grid framework is supposed to work, or what pages already have a treatment for a secondary action form button, and it will save you or someone else from appending redundant and unnecessary rules to your CSS.

The choice to use documentation has a bonus side effect of being a great place to park explanations that otherwise must be included as CSS comments. CSS comments are great for sectioning off chunks of long CSS files, but verbose comments that are used to explain design choices can add to file size, and might be better suited to a markup and style guide. Documenting your code using CSS comments within your working file is most definitely better than nothing at all, but housing that material in separate documentation is a great way to keep the code focus and free from bloat.

7. Make use of compression

Some great applications have been created to compress and optimize CSS for you, allowing you to serve a human-unreadable but still browser-friendly files that are a fraction of the origional working copies. Applications like CSSTidy and the YUI Compressor can compress whitespace, detect and correct for CSS properties that are overwrite each other, and look for opportunites to use CSS shorthand that you may have missed. (These types of applications are excellent sources to read about, if for no other reason, to learn what things you can further do by hand).

Even popular text editors like BBEdit, TextMate, and TopStyle, can help format your CSS files to your liking. There are also options serve zip versions of your CSS files using PHP. You can find more CSS compressors and optimizers in the post List of CSS Tools.

It is important to note that these applications do their best to minimize errors, but they aren’t always perfect. Also, they work best when browser hacks are not included in the file set (which is yet another reason to keep those hacks external).

There is one last type of application that can help prune CSS file size I’d like to mention. It can crawl a web site and log which CSS rules and declarations are not being applied, then bring these to your attention. Unfortunately, this tool hasn’t been inventend yet, but I would gladly pay for such a application.

I can recall times when I’ve been afraid to delete certain rules because there is no documentation that explains to me that those selectors are leftover from previous iterations of development. If an app can bring those rules to my attention, that will help with maintenance and keeping CSS files lean.

Conclusion

Clean and optimized code is important not just for file size, but for maintenance and readability as well. The principles mentioned above are good considerations not just for CSS, but can be applied to HTML, JavaScript, and other programming languages. CSS files are not as prominent as the rendering of your web site to an end-user, but consideration of the above principles can help with both the user experience (in the form of smaller file sizes) and the developer experience (cleaner code). Apply these principles to your current and future projects, and and you will surely appreciate the efforts.


Herramientas online para limpiar, chequear y optimizar CSS

  • Autor: administrador
  • Archivado bajo: Herramientas, Css
  • Fecha: Aug 26,2008

Dependiendo de tu forma de trabajar y la complejidad de tu proyecto, si eres ordenado o no, te puedes encontrar con uno o varios css que ni tú eres capaz de entender que ocupa demasiado y que hay elementos redundantes o sobrantes.Para poner un poco de orden, eliminar lo que sobre y comprobar que cumple los estándares puedes utilizar estas herramientas web:

Optimizar y comprimir:

Dar formato:

Validación:

  1. + Web-Based Tools for Optimizing, Formatting and Checking CSS

9 Top CSS Essential Skills That Every Web designer Should Learn

  • Autor: administrador
  • Archivado bajo: Css
  • Fecha: Aug 26,2008

This post is dedicated to elementary & intermediate CSS learners. If you’re going to learn CSS from scratch, you’ve probably seen a lot of techniques, tricks & tutorials so far. In this post I’ve written my own approach to the most essential CSS skills that every web designer should learn. I really love the articles below and liked to share them with you. Hope you enjoy it!

1- Making CSS Layouts

2- Styling & Using Lists

lists

3- Understanding Box Model & Positioning

boxmodel

4- Better CSS Typography

typography

5- Styling Forms

form

6- Using CSS Frameworks

frameworks

7- Optimizing & Best Practices

bestpractice

8- CSS Hacks & Tricks

hacks

9- CSS Buttons, Boxes & Round Corners

button-5


IE tiene un número máximo de ficheros css que le puedes añadir

  • Autor: administrador
  • Archivado bajo: Css
  • Fecha: Aug 26,2008

En una de las webs que estamos desarrollando tenemos un archivo de css para corregir los errores de IE usando comentarios condicionales (como en todas las otras webs). Resulta que de repente no funciona y pongas lo que pongas no hace caso. Es más, luego veo que en algunas páginas funciona y en otras no.

Pues el problema estaba en que IE6 (por lo menos, IE7 ahora no lo sé) tiene un límite en en número de ficheros css que le puedes añadir y resulta que el fichero que arreglaba los bugs de IE6 estaba fuera de él. En un issue de Drupal ponen que el límite está en 31 aunque yo he contado los mios y llegan a 27. En esa página hacen mención al método createStyleSheet que tal vez sea el que use Explorer internamente para añadir los ficheros css externos aunque no lo tengo muy claro. Tal vez haya contado mal yo y si tengo más de 31 ficheros.

Supongo que algunos pensaréis que son una burrada de ficheros css pero cuando desarrollas en Drupal no son tantos. Hay muchos módulos que añaden los suyos y luego siempre va bien separarlos según sus funciones. Y cómo Drupal te permite juntarlos todos en uno luego no hay problema de rendimiento pero eso se hace con la web en producción, en desarrollo no se puede por que hay problemas de cache y no ves los cambios inmediatamente por lo que se desconecta hasta estar listos.

visto en http://carlos.rinconsanchez.com


HTML Purifier es una librería escrita en PHP5 que filtra nuestro código HTML y lo “purifica” eliminando etiquetas innecesarias o maliciosas en entradas de datos y verificando que el resultado sea válido según las especificaciones del W3C.

Otro punto importante a su favor es que esta también en forma de plugin para algunos de los más conocidos CMSs como:

  • Phorum
  • MODx
  • Drupal
  • Wordpress
  • CodeIgniter

Según su página web es una utilidad:

  • Segura: Remueve el código malicioso (XSS) de las aplicaciones.
  • Limpia: Te asegura un código que sigue los estándares Web.
  • Abierta: Está hecha bajo la filosofía Open Source, esto lo hace altamente personalizable.

Puedes descargarla como una aplicación aparte o guardar en tus favoritos esta demo que estara disponible en su página web.


Hacks para IExplorer,Mozilla y Safari

La más común al hacer una página web es que en un navegador se vea bien y en otro se vea diferente, este fenómeno ocurre porque cada navegador interpreta los estándares de una manera diferente incluso en sus distintas versiones, sobre todo en Internet Explorer (IE). Es aqui cuando requerimos la aplicación de diferentes hacks o trucos para que nuestra página funcione bien en los diferentes navegadores.

A continuación veremos unos cuantos trucos, hacks y consejitos a la hora de trabajar con CSS que seguramente nos quitaran un dolor de cabeza en algún momento y nos mantendran dentro de los estándares web.

Image

SELECTORES ESPECIFICOS PARA CADA NAVEGADOR

Estos son unos cuantos selectores que nos permiten cambiar un estilo en un navegador determinado, pero no en los demás.

IE 6 y anteriores:

* html {}

IE 7 y anteriores:

*:first-child+html {} * html {}

IE 7 solamente:

*:first-child+html {}

IE 7 y navegadores modernos solamente:

html>body {}

Navegadores modernos solamente (IE 7 NO):

html>/**/body {}

Versiones recientes de Opera y anteriores:

html:first-child {}

Safari:

html[xmlns*=”"] body:last-child {}

Para usar estos selectores, debes colocarlos despues del estilo que quieres modificar asi:

#cuadro-contenido{
width: 300px;
height: 150px;
}

* html #cuadro-contenido{
width: 250px;
}

Esto anula el estilo y cambia el ancho por 250px en IE6 y sus versiones anteriores
PNG’s TRANSPARENTES PARA IE6

Como bien sabemos IE6 no soporta la transparencia de las imagenes en formato PNG, generalmente saca un recuadro gris que daña todo nuestro diseño. Para que nos funcione la transparencia necesitamos usar un filtro que solo funciona para IE6 aplicando los selectores del punto pasado asi:

* html #estilo-imagen {
background-image: none;
filter:progid:DXImageTransform.Microsoft.AlphaImageLoader(src=”nombreDeArchivo.png”,                     sizingMethod=”escala”);
}

REMOVER RECUADRO PUNTEADO EN LOS HIPERVINCULOS:

Firefox produce un recuadro punteado cuando hacemos click en un link o hipervinculo.

Image

Esto es muy fácil de arreglar, simplemente agregamos la propiedad outline:none en la etiqueta a

a{
outline: none;
}

ANCHO A ELEMENTOS INLINE

Si le aplicas un ancho a un elemento inline, solo funcionará en IE6. Esto es una falla del navegador ya que los elementos inline no deberían necesitar tener un ancho asignado. Sin embargo el asignarselo es algo muy útil por ejemplo si quieres todos los labels de un formulario del mismo ancho.

Todos los elementos HTML son de algun tipo, block o inline. Los elementos inline son los span, a, strong, em, entre otros. Los elementos de tipo block son los div, p, h1, form, ul, etc.

Nosotros podemos cambiar el ancho de un elemento inline. El truco esta en cambiar el elemento de tipo inline a tipo block.

 span {
width: 150px;
display: block
}

Aplicando la propiedad display:block convertimos el span de un elemento inline a uno de tipo block, permitiendonos asi cambiar su ancho. Lo unico que debemos tener en cuenta es que los elementos de tipo block comienzan en una nueva linea por su margen y relleno por defecto, aunque tenemos la ventaja tambien de usar flotaciones si lo requerimos.

CENTRAR UNA PAGINA CON ANCHO FIJO

Para centrar una página web dentro del navegador, aplicale una posición relativa al div contenedor de la página y colocale una margen automática.

#contenedor {
margin: auto;
position: relative;
}

TECNICA PARA REEMPLAZAR IMAGENES

Para cumplir los estándares, siempre es mejor usar texto en los encabezados en vez de imágenes. Pero la mejor practica para poner las imágenes a nuestros encabezados es ubicar la imágen en el fondo con un texto oculto dentro de un div. Esto es muy útil para los lectores de pantalla, para el SEO, lectores de feeds, dispositivos móviles, o si simplemente desactivan los estilos css de nuestra página ya que alli solo se  verá el texto.

HTML:

<h1><span>Main heading one</span></h1>

CSS:

h1 {
    background: url(heading-image.gif) no-repeat;
     }
      
h1 span {
    position:absolute;
    text-indent: -5000px;
    }

Como pueden ver usamos html normal para la etiqueta h1, y con css reemplazamos el texto por la imágen poniendo el texto 5000px a la izquierda, haciendolo invisible al usuario, para probar el efecto visualiza tu página en el navegador y luego desactiva los estilos css.

ANCHO MINIMO

Otro error en IE es que no soporta el atributo min-width. Este es extremadamente útil, especialmente para plantillas flexibles que tienen un ancho de 100% y no queremos que el navegador las contraiga. Para todos los navegadores exceptuando IE6 solo necesitas especificar min-width:Xpx; asi:

.contenedor {
min-width:300px;
}

Para IE6 es un poco más complicado, para empezar nesecitamos crear dos divs, uno dentro del otro

<div class=”contenedor”>
     <div class=”contenido”>Content</div>
</div>       

Indicamos el min-width del div exterior

.contenedor {
min-width:300px;
}

Ahora viene el hack, nesecitamos insertar el siguiente código

* html .container {
border-right: 300px solid #FFF;
}

* html .holder {
display: inline-block;
position: relative;
margin-right: -300px;
}

Cuando la ventana del navegador es redimensionada, el ancho del div exterior se reduce junto con el ancho del borde que no permite que se encoja más de la medida. EL div interno hace lo mismo deteniendose igual a la medida. Asi pues el div exterior define el ancho mínimo para el div interior.

ESCONDER EL SCROLL HORIZONTAL

Para remover la barra de scroll horizontal, debemos insertar la propiedad overflow-x: hidden; en el body así:

 body {
     overflow-x: hidden;
 }

Esto es muy útil cuando tenemos una imágen o una pelicula de flash con un ancho muy largo en el navegador.

Esperamos que pongas en práctica estos trucos cuando te sean necesarios y que te sean de mucha utilidad.