Archive for the ‘Diseño’ Category

Metadatos en Html

Thursday, August 21st, 2008

Metadatos en html

Si hay algo en lo que el W3C siempre insiste es en el significado del documento. Desde el punto de vista del W3C, internet debe ser información estructurada, y el html debe ser la herramienta para lograr esa estructuración.

Una página web debe ser un conjunto de datos organizado con sentido. Las etiquetas html deben insertarse con este fin organizativo (dejando la presentación para otros lenguajes, CSS). La sola lectura del código debería ofrecer información relevante sobre el documento. Se trata en definitiva de organizar internet, escribiendo páginas que contengan información sobre si mismas, de forma que pueda mecanizarse su clasificación y catalogación. El futuro de la metainformación pasa por la web semántica y por XML, pero mientras tanto podemos avanzar por ese camino con los metadatos.

Los metadatos (información sobre la información) no se visualizan, pero estan integrados en el documento ofreciendo información variada: desde el tipo de formato utilizado (html, xml …) hasta el autor, editor con el que se ha confeccionado, información para los buscadores, etc.

La etiqueta meta

La forma usual de insertar metadatos en el documento es por medio de la etiqueta <META> en la sección <HEAD> de la página.

Esta etiqueta es de aquellas de las que llamabamos “elementos vacios” porque no lleva etiqueta de cierre. Su estructura es la de una declaración propiedad:valor. Por ejemplo:

<meta name=“generator” content=“HTML-Kit” />

etiqueta que contiene la metainformación de que el documento ha sido escrito usando dicho editor.

No existe ninguna regla acerca de la informacion que puedes o no puedes incluir en las metatags. El standard html define la estructura de una etiqueta META, pero no sus valores. Es perfectamente válido que inventes tus propias etiquetas META; sin embargo dado que no se visualizan en el navegador, y que realmente solo se aprovechan por los buscadores y otras herramientas informáticas (que lógicamente solo entienden las etiquetas META mas difundidas) tampoco tiene mucho sentido crear tu propia metainformación, salvo para uso propio.

Etiquetas META mas usuales

description

<meta name=“description” content=“Esta es la mejor pagina del mundo mundial” />

Mediante esta etiqueta podemos incluir como metadato una descripción de nuestra página. Esta descripción puede ser leida y utilizada por algunos buscadores
La etiqueta <meta> admite el atributo lang, que nos permite ofrecer información sobre el idioma:
<meta name=”description” content=”Esta es la mejor pagina del mundo mundial” lang=”ES” />

keywords

<meta name=“keywords” content=“mp3, free, FREE, download, britney, spears” />

Las palabras clave son aquellas que resumen de forma significativa el contenido de la pagina. Por ejemplo keywords adecuadas para ignside.net podrían ser “noticias, internet, manuales, html”

Las dos etiquetas META que acabas de ver son las mas importantes. Como los buscadores leen estas etiquetas y pueden juzgar acerca de la importancia de la pagina segun ellas, existe una auténtica industria montada sobre estas dos sencillas lineas. Una buena selección de descripción y keywords puede suponer que tu página aparezca muy arriba en las búsquedas, y eso supone mucho dinero para las páginas comerciales.

Naturalmente no es tan sencillo … a cualquiera se le ocurriria que unas keywords como las del ejemplo atraerian visitantes como moscas … por eso mucha gente, en lugar de hacer páginas atractivas, se conforma con incluir keywords atractivas, pensando que actuarán de cebo, y los buscadores incluyen filtros para evitarlo. Por ejemplo, el filtro mas sencillo es comprobar si en el texto del documento aparecen las palabras usadas como keywords.

HTTP-EQUIV

Las páginas web se distribuyen por internet mediante el protocolo http, que viene a regular el diálogo entre el servidor y el navegador. Pues bien, con estas etiquetas, el autor de la página puede predeterminar aspectos de este diálogo.

Su sintaxis general es:

<meta http-equiv=“” content=“” />

content-type

<meta HTTP-EQUIV=“content-type” CONTENT=“text/html; charset=ISO-8859-1″/>

Con esta etiqueta META indicamos al navegador el tipo de documento que es nuestra página: si es un documento html, o un documento de texto plano, o cualquier otra cosa:

En el ejemplo, significaria que es un documento texto-html y que usa un juego de carácteres ISO-8859-1 (esto es, que no usa letras chinas, ni cirílicas, ni nada raro). Esta información es útil para que el navegador de nuestros visitantes sepa que juego de carácteres debe emplear.

refresh

<meta http-equiv=“refresh” content=“5″ />
<meta http-equiv=“refresh” content=“5;url=http://www.ignside.net/otra.htm/” />

Mediante esta etiqueta y el valor refresh podemos indicar al navegador que debe recargar la página una vez transcurridos el tiempo de segundos especificado. En la primera linea se ve un refresh simple, con orden de recarga a los cinco segundos. En la segunda línea, un refresh con redirección. El navegador debe refrescar la página a los cinco segundos, recargando en su lugar la especificada.

Advierte como las comillas abarcan todo el contenido, incluyendo segundos y url.

expires

<META HTTP-EQUIV=“Expires” CONTENT=“Tue, 04 Dec 2000 21:29:02 GMT”>

Mediante la orden expires informamos de la vigencia del documento. Su utilidad principal es la de evitar que el navegador guarde indefinidamente en caché una página forzandole a cargar las nuevas versiones.

La fecha debe estar necesariamente en formato RFC840 (GMT), es decir:
dia_de_Semana, DD-Mon-YY HH:MM:SS TIMEZONE(Greenwich) todo ello en inglés

Por ejemplo Fri, 01 Jan 2003 07:20:55 GMT

Si la fecha está expresada en un formato distinto, el valor de expires será interpretado como now, es decir, se fija una caducidad inmediata.

pragma

Ordena al navegador que no almacene una copia cache de la página. Util cuando se trata de páginas dinamicas cuyo contenido cambia frecuentemente. Su unico valor aceptable es no-cache

<meta http-equiv=“pragma” content=“no-cache” />

set-cookie

Mediante esta metatag podemos enviar una cookie al navegador del usuario. Si contiene fecha de expiración, el navegador la conservará en el disco duro hasta dicha fecha; en caso contrario, se borrará al terminar la sesión de navegación.

<META HTTP-EQUIV=“Set-Cookie”
CONTENT=“nombre_cookie=valor_cookie;expires=fecha_valor;
path=/” />

Window-target

Sirve para especificar el nombre de la frame donde la página ha de ser cargada. Por ejemplo:

<META HTTP-EQUIV=“Window-target” CONTENT=“_top”>

En fin, estas son las mas corrientes de entre las destinadas a tratar con los servidores; menos usadas son

<META HTTP-EQUIV=“Content-Script-Type” CONTENT=“text/javascript”>
<META HTTP-EQUIV=“Content-Style-Type” CONTENT=“text/css”>

que informan respectivamente del tipo de lenguaje script utilizado, y del uso de CSS

Mas etiquetas, por favor

robots

Podemos dar instrucciones a los robots de los buscadores acerca de que páginas pueden incluir en sus bases de datos y cuales deben saltarse. Sus valores son index que indica que la página debe ser indexada; noindex es justo lo contrario, el robot debe saltarse esa página; follow pide al robot que siga los links que existan en la página e indexe las páginas resultantes; nofollow lo contrario. Los valores por defecto se entiende que son index, follow (separados por coma).

<META NAME=“robots” CONTENT=“noindex,follow”>

Hay otras formas supuestamente mejores de tener tratos con los robots. Puedes enterarte como aqui.

PICS

Nada que ver con fotografias aqui (o si, indirectamente).

La etiqueta PICS se usa para facilitar la labor de filtrado de la página con arreglo a su contenido, advirtiendo de que puede tener, por ejemplo, contenido sexual, violencia o lenguaje ofensivo. Por ejempo:

<META http-equiv=“PICS-Label” content=‘(PICS-1.1
“http://vancouver-webpages.com/VWP1.0/” l gen true comment “VWP1.0″
by “webmaster@ignside.net” on “2002.11.10T07:34-0800″
for “http://www.ignside.net” r (MC -1 Gam -1 Com 0 SF 0 Edu -2 S 0
Can 0 V 0 Env 0 P 0 Tol 0 ))’ />

De utilidad dudosa (ya que la metatag por definicion la escribe el autor de la página), si tienes interés puedes probar este generador.

anti smart-tags

Las smart-tags fueron un invento de microsoft que sencillamente permitía alterar el contenido de una página web, insertando, insertandose enlaces aqui y allá al libre albedrío de sus creadores. El problema es que ya no es el autor de la página quien decide donde incluye links (y sobre todo, hacia donde enlaza) sino la propia microsoft. Naturalmente se levantó un clamor contra la idea, que de momento está aparcada.

<meta name=“MSSmartTagsPreventParsing” content=“TRUE”>

99 recursos para diseños 2.0

Sunday, August 17th, 2008

Aqui teneis de la mano de webusabilityhelp.blogspot.com 

http://webusabilityhelp.blogspot.com/2007/11/99-resources-for-web-20-design.html

BADGES

Web 2.0 Badges - Un set gratuito de badges para descargar.
Fresh Badge - Genera rapidamente tus badges.
adClustr - Crea tus badges.
Deziner Folio - Coleccion de varios badges.
BittBox - Badges vectoriales.
Official Seal Generator - Alternativa al tipico badge.
Photoshop Tutorial - Lecciones rapidas en photoshop para crear nuestro badge.
Glossy Photoshop Tutorial - Crea tu badge glossy con este tutorial.

BOTONES

Mi  Boton cool - Un bonito editor online que nos ayudara rapidamente a crear nuestro boton .
Adam Kalsey’s Button Maker - Herramienta online de Adam Kalsey para crear botonos.
Button Maker from Blog Flux - Crea tu boton desde el blog de Flux.
Crea tu boton brillante - Similiar al anterior editor online de creacion de botones.
Botones CSS - Escoge el texto, el fondo y los bordes para tu web.
Buttonator - Una alternativa de pago para crear nuestros botones, muy interesate.
RSS Button Maker - Crea tu boton RSS.
Button Boost - Una pequeña herramienta para generar pequeños botones.
ButtonGenerator.com - Crea menus y botones de navegacion para tus webs.
Crystal Button - Así de facil, botones de cristal.
Chicklet Creator - Crea botones para subscribir a tus visitantes a tus feeds.

ESQUINAS REDONDEADAS

Esquinas redondeadas es una de las acciones tipicas de las web 2.0. Aqui tienes algunas herramientas online para crearlas, pero existem muchas mas.

RoundedCornr
Corner Shop
Spiffy Box
Canvas Corner
Spanky Corners
Sliding Doors Text Box
Smart Rounded Corners
Rounded Corners in CSS
News List

LOGOS

Crea facilmente tu logo para tu web totalmente online, es simple, rápido, fácil y 2.0.
Web 2.0 Logo Creator
Web 2.0 Logo Creatr
Web 2.0 Logo Creator
Web 2.0 Stylr

ICONOS

Una web 2.0 no puede ignorar los iconos. Aqui dispones de una gran coleccion de iconos listos para usar en tus projectos.
UtomBox - Coleccion de iconos web 2.0.
Feed Icons - Iconos para RSS estandars.
Map Icon Factory - Crea ty icono para tu sitemap.
Perishable Press - Una bonita coleccion de iconos RSS.
Glass Style - Mas iconos RSS
Snap2Objects - Iconos vectoriales RSS.
31 Sources of Quality - Iconos gratis, 31 iconos de calidad

IMAGENES CON DEGRADADOS (ideal para fondos de celdas)

Otra de las acciones necesarias para tener un buen diseño web 2.0 son los degradados.

Gradient Image Maker
Gradient Generator
Online Gradient Image Maker (OGIM)

ALGUNAS OTRAS COSILLAS INRESANTES

Speech bubbles are commonly used for styling comments or blockquotes.
Will Mayo
Bubblesnaps
CSS Play
XHTML Speech Bubbles
WigFlip
Fluid CSS Speech Bubbles
MySpace Speech Bubble Generator
Photoshop Tutorial

IMAGENES DE FONDO

Herramientas online para crear tus backgrounds.

Stripe Designer - Crea facilmente tus imagenes.
Tartan Maker - Crea imagenes de fondo online.
Texture Generator - Crea texturas con las siguientes imagenes para tus fondos de web.
All Free Backgrounds - Escoge el fondo que quieras de esta galeria.

COLORES

Quizas sea la parte mas importante para algunos, “el color”.
Web 2.0 Color Pallete - Colores populares en los estandares 2.0.
Color Schemer Gallery - Tienes problemas escogiendo un esquema de color para tu pagina, elige el que quieras de esta galeria..
COLOURlovers - Mas ejemplos de combinaciones de colores.
Website Color Picker - Combina rapidamente combinaciones de colores.
I Like Your Colors - Elige los colores que vas a usar en tu web.

NAVEGACIÓN

CSS Menu Generator - Easily create attractive CSS menus.
Listamatic - Collection of CSS menus.
List-O-Matic - Create your own CSS menus.
List-U-Like - Another tool to create your own navigation bars.
Tabs Generator - Create tabbed images for navigation.
Flash Buttons - Create navigation menus with flash buttons
CSS Play - An extensive collection of CSS menus.
Exploding Boy - Tabbed CSS navigation menus.
CSS Navigation Menu Generator - A tool to help you create your own menu.

FAVICONS

Favicon Generator - Create your own favicon from an image on your computer.
Favicon from Pics - Create a favicon from a photo.
Favicon Editor - Upload a photo, create a favicon.
Favicon.cc - Another option for favicons.
Photoshop Tutorial - Creating a favicon with Photoshop.

CHARTS

PHP/SWF Charts - Create attractive charts.
amCharts - Flash charts.

OTHER

Avatar Maker - Create and edit an avatar.
Shrink Pictures - Create an avatar from your photo.
ScaleNine - Collection of skins and themes created for Flex and Adobe AIR.
VectorMagic - Converts bitmap images to vector art.
Templatr - Create a layout.
PsycHo - Blog template generator.
Web 2.0 Generator - Creates layouts.
Typetester - Compare fonts on-screen.
BlogPoll - Create a free poll for your blog.
RSSxl - Convert an HTML page to RSS.
Meta Tag Generator - Easily create meta tags for your pages.
URL Rewrite - Create search engine-friendly URLs for dynamic pages.
.htacces generator - Quickly create an .htaccess file.
Thumbnail Generator - Create thumbnails for a large amount of images.
Reflection.js - Adds reflections to your photos.
Drop Shadow - Improve your images with a drop shadow.
CSS Sprite Generator - From Website Performance.
Vecteezy - Stupid name. Cool vectors.
Brusheezy - Photoshop brushes.
PSBrushes.net - More Photoshop brushes.
deviantART - Photoshop brushes at deviantART

Related Link:

99 Useful Resources for Graphic Designers
Download AutoCAD 2007 for free
A to Z Online Resources for e-Learning
A Preview of HTML 5
Best Selling Graphic Design related Books
25 Headline Formulas That Have Blessed Web 2.0
Website Design for your Customers - It’s not what you want

Hacks para IExplorer,Mozilla y Safari

Sunday, August 17th, 2008

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.

Pasar de Psd a Css en pocos pasos (2 de 2)

Saturday, August 16th, 2008

From PSD to CSS/HTML in Easy Steps - Part 2

Welcome to part 2 of our tutorial. In part 1 we created the basic structure of the site on which we are going to build our photography site. This is the second in our 4 part series on how to take a PSD file and convert it into a fully CSS based html page. These are the first in a series of tutorials in which we build a fully working Photography site, all in clean Xhtml and CSS. All the code, templates and files are available for you to play with, and we encourage you to download and play with what is provided. The design template is licenced under the creative commons licence.

We are still working from the same PhotoShop file (PSD) and in this part of the tutorial we are going to flesh out the layout a little more and by the end it should be looking a lot more like the design we are working from.

In case you need reminding or are new to this series of articles, below is what we are aiming to achieve. Here is the first PSD to CSS html tutorial

PSD Layout

PSD to CSS part 2

At the end of part 1 we finished by creating the very top Navigation of the site, part 2 is going to start with the logo and tagline below the top nav. Lets get going..

Logo and Tagline

The first main graphical element is the logo and tagline that is reproduced in Figure 2 below.

Figure 2

Logo and tagline

Choices, choices , choices……

As with any graphical element you should look at ways that sections can be repeated to save on file size. Unfortunately for this element there is no uniform section that can be repeated as there is an undulating wave effect covering the whole layout. Also there are rounded corners and beveled edges to consider and the number of images used would be many.

Time to compromise….

In order to simplify things I am going to place most of the image in one go. I will remove the logo on the left side and also remove the lorem ipsum text from the right side. This will leave us with a background as shown in Figure 3.

Figure 3:

Tagline background

We can then place the company logo on the right hand side and also turn it easily into an anchor that will point to the home page as per usual.

The lorem ipsum text was removed from the image because it may be changing on different pages throughout the site so I wanted to make it easier to adjust later on. The text is clearly graphical and as it is part of the logo I am going to place it as an image but use some text replacement techniques so that the content is still available to search engines and people alike. The image will have to be placed exactly to match the background but this shouldn’t be too difficult as you can compare the positions from the positions that you cut out from the PSD.

I am going to place the image shown in Figure 3 as a background image and then overlay the logo as a foreground image because I think the logo is important. As mentioned the lorem ipsum tagline text will be an image but will have a text alternative for screen readers etc. Any image replacement fails at some stage but some are better than others and again its another choice that only you can make as to whether you should follow this route or not.

There is another issue of what elements to use for the logo and tagline?

Some people advocate using an H1 element for the logo on the first page and some will argue against it. I think that an H1 should describe the page content exactly and if the logo has a text equivalent to the main heading then it could be used. In our page the logo says “Sanke Photography” but further down the page we have another heading that says Sanke Photography Tutorials. So which is it to be?

I can’t answer this question for every case but it seems to me that the site heading should be Sanke Photography and the sub heading is “Sanke Photography Tutorials”. Therefore in this case I am going to put the logo in an H1 element but to hedge my bets I am also going to include the tag line within the h1 as it will add extra content and meaning to the subject. However , I would have no objections to having the logo and tag line in paragraph tags and the main heading as the “Sanke Photography Tutorials” heading which is further down. As you can see I’m sitting on the fence here a bit so feel free to make your own mind up.

We are going to use an element called #tagline which will hold our logo and tagline so we need to create an element of the correct dimensions to hold our background image. We also need an overlapping effect due to the graphic on the right of the image that rises up alongside the text. We can create this with a negative top margin on #tagline which will pull the image upwards and next to the navigation. To avoid stacking issues we will set position:relative on the nav and on #tagline and then set the z-index on each so that the nav has a higher z-index and sits on top of the background on #tagline. This is accomplished as follows.

PLAIN TEXT

CSS:

  1. ul#nav{

  2.     position:relative;

  3.     z-index:2

  4.     }

  5.     #tagline{

  6.     width:975px;

  7.     height:116px;

  8.     margin:-40px 0 0 0;

  9.     background:url(images/tagbg.jpg) no-repeat 0 0;

  10.     position:relative;

  11.     z-index:1

  12.     }

Remember that only positioned elements can have a z-index applied so you need to add position:relative if the element isn’t already positioned. The other use of position:relative is that it sets a stacking context for further positioned elements and allows us to place our logo and tagline absolutely into position within this element and not based from the viewport.

The image replacement method we will use is to place the image in an inner element and then drag it on top of the text content to hide it. As long as we set a width that matches the height and with of the image we can then set overflow to hidden and any text that spills out will be hidden. This allows for the text to be available to screen readers and users alike should images or CSS be turned off. We do this for both the logo and the tagline and end up with HTML and CSS as follows.

PLAIN TEXT

HTML:

  1. <div id=“tagline”>

  2. <h1><a href=“#”>Sanke Photography<em><img src=“images/logo.jpg” title=“Sanke Photography logo” alt=“Sanke Photography” /></em></a><span>Sanke Photography simply the best for your photography tutorials<em></em></span></h1>

  3. </div>

PLAIN TEXT

CSS:

  1. /* tagline code */

  2. #tagline{

  3. width:975px;

  4. height:116px;

  5. margin:-40px 0 0 0;

  6. background:url(images/tagbg.jpg) no-repeat 0 0;

  7. position:relative;

  8. z-index:1

  9. }

  10. #tagline a,

  11. #tagline a em{

  12. position:absolute;

  13. width:218px;

  14. height:68px;

  15. overflow:hidden;

  16. left:27px;

  17. top:39px;

  18. }

  19. #tagline a em{

  20. cursor:pointer;

  21. left:0;

  22. top:0;

  23. /*background:url(images/logo.jpg) no-repeat 0 0; use this as an alternative to image in the html*/

  24. }

  25. #tagline span,

  26. #tagline span em{

  27. position:absolute;

  28. width:383px;

  29. height:51px;

  30. overflow:hidden;

  31. left:408px;

  32. top:51px;

  33. }

  34. #tagline span em{

  35. left:0;

  36. top:0;

  37. background:url(images/tagline.jpg) no-repeat 0 0;

  38. }

Images used:

tagbg

logo

tagline

The cursor:pointer is added to the em that is inside the anchor to help IE remember that it is still an anchor and show the correct cursor.

If we look closely at the html we can see that the h1 has no real styling and therefore we can get rid of the div surrounding the h1 and apply the ID directly to the h1 instead as follows. We simply give the H1 the tagline ID and remove the div surrounding it.

PLAIN TEXT

HTML:

  1. <h1 id=“tagline”><a href=“#”>Sanke Photography<em><img src=“images/logo.jpg” title=“Sanke Photography logo” alt=“Sanke Photography” /></em></a><span>Sanke Photography simply the best for your photography tutorials<em></em></span> </h1>

The only CSS change is to remove the following code which is now redundant.

PLAIN TEXT

CSS:

  1. #tagline h1{

  2. margin:0;

  3. }

The layout so far can be viewed here and you should check it matches with yours if you are working along with this. Just view source and you can see the code as the relevant CSS is still embedded in the head.

Figure 4 shows the result of our work so far.

Figure 4

The layout so far

That looks pretty good and at this stage you check in as many browsers as you can to make sure all is well. You should also try resizing the text to see if there is any overlap that is unacceptable. There are bound to be some minor things on text resize but you should endeavor to always keep the page usable within reasonable limits.

Figure 5 shows the text resized to smallest and largest in IE6 and all is looking good.

Figure 5

Text resize

Search Box and Background Image

Moving on the next element which is the search box and the main page image graphic we need to decide what quality this image will need to be. Its a big image and will be a very heavy file size. I have optimised it down to about 50k (which is still large) but it was originally about 4 times that size. Because this is a photography site then we probably need to make sure the images are of a good quality and at this stage I would cut the image out and make 2 versions in case the client wants a better quality at a later stage. So when you save a big image like this do yourself a favour and save a higher quality version also just in case.

Remove the search box from the image and cut the image to the right dimensions. It is also worth looking a little further down the page and you will see that the next elements has rounded corners and beveled edges so we can save some time by including the top of the next element with the search box image and end up with an image like this and as seen in figure 6.

Figure 6

Search background

As this element is a fixed width and height and there is not really any text that will break out when resized so we can place this whole image as one background image with a fixed width and height. That makes things very easy and we can still overlay our search box in position using absolute positioning. In order to make use of absolute:positioning inside this element we will need to make sure once again that we set position:relative on the parent as follows.

PLAIN TEXT

CSS:

  1. #search{

  2. width:975px;

  3. height:275px;

  4. background:url(images/search-bg.jpg) no-repeat 0 0;

  5. position:relative;

  6. }

PLAIN TEXT

HTML:

  1. <div id=“search”></div>

That was pretty painless and our layout is now starting to take reasonable shape as seen in figure 7.

Figure 7

Search background

Main 3 column Section

We start to move on to some more complex areas and this is the main part of the site with three columns across the screen. The columns can simply be floated across but we are going to have to think about 3 main things.

  • 1) The vertical faded gradient that is on each column.
  • 2) The 3 equal columns that will match each others height.
  • 3) The bottom round corner on the right column

Issue one has two solutions that we could use. We could take a vertical slice of each of the columns in turn of about 5px x 250px which contains the whole gradient. We would then need to repeat that image in each of the floated columns as required. The only problem with this method is that the PSD shows a slight gradient horizontally as well and also shows fading beveled edges. If we were to carry on with these small slices we would need at least another 4 images for each edge as well and forget about the horizontal gradient altogether.

The second solution is to simply cut the whole background out in one go. While this may seem a bit heavy handed we can actually cut a rather big image of 975px x 270px but optimise it right down to about 3k with little loss of color. This saves multiple background images and gets us much closer to the original design. This is the method we will use and results in this image being produced and can be seen in Figure 8. As with all the other images I have cut some of the background with the image to allow for the slight background fade.

Figure 8

3 column top background

Issue two can be tackled by creating a horizontal slice that contains all three column colours and we can repeat this on the main parent of this section that is holding all three floats. We create the slice by ensuring that we slice from the finishing colour of the vertical gradient. This gives us the following image.

Figure 9

3 column slice

This image will be repeated on the y-axis of the parent in this section and will provide full length column colours that always remain equal with each other. We will then overlay on the top part of this image the larger gradient image as shown in figure 8 so that we get the good gradient effect we wanted. This will mean that an extra element will have to be nested to hold this image but it is worth it.

As the page expands the repeating slice comes into play and if we have cut the images out correctly there should be a seamless transition between the two images.

Therefore the html we need will now be as follows:

PLAIN TEXT

HTML:

  1. <div id=“main”>

  2. <div id=“content” class=“clearfix”>

  3. <div id=“col1″></div>

  4. <div id=“maincol”></div>

  5. <div id=“col2″></div>

  6. </div>

  7. </div>

The nested element named #content has been added to hold the big gradient image while #main will hold the repeating slice. As #content will also contain our three floated columns we need to make sure the floats are cleared and we can do that simply by adding our clearfix class to the element in question. This will ensure that the floats are cleared and the background of the parent extends with the floats and isn’t left behind.

Floats are removed from the flow and will float out of their parents reaches unless you do something to stop them. I’m quite happy to use the ‘clearfix’ method in this case but you should be aware of the various issues associated with each method.

The CSS we need is simply as follows:

PLAIN TEXT

CSS:

  1. #main,#content{width:975px}

  2. #main{background:url(images/3col-bg.jpg) repeat-y 0 0}

  3. #content{

  4. background:url(images/3col-top.png) no-repeat 0 0;

  5. min-height:270px;

  6. }

  7. * html #content {height:270px}/* for ie6 and under*/

The hack for IE6 and under is because it doesn’t understand min-height but luckily does treat height almost as min-height which suits our purpose nicely. We need a min-height here because of the vertical gradient and if we don’t allocate enough height our repeating slice will repeat from a section that doesn’t match.

The result of the above code can be seen in figure 10.

Figure 10

Three columns

You can view the state of play here in a real example also.

To allow content to be pout into these columns just requires us to measure the columns and apply the necessary margins to our floats to make then all line up where we want. the measurements I have come up with are as follows:

PLAIN TEXT

CSS:

  1. #col1{

  2. width:207px;

  3. margin:0 28px 0 18px;

  4. display:inline;/* cure IE6 double margin bug*/

  5. float:left;

  6. }

  7. #maincol{

  8. width:444px;

  9. margin:0 48px 0 0;

  10. float:left;

  11. }

  12. #col2{

  13. width:180px;

  14. float:left;

  15. margin:0 50px 0 0;

  16. display:inline;/* cure IE6 double margin bug*/

  17. }

You must make sure that all these dimensions fit in your container otherwise floats will drop or be misplaced. We have 975px to play with and the widths and margins for the floats adds up to exactly 975px. There is also a fix in the code for IE6 and under which will double the margins on floats where their side edges meet their parent’s container. The fix is to add display:inline to the floats in question and miraculously fixes the problem. Floats are display:block and cannot be made to be display:inline so the fix is really nonsense and should have no effect but luckily for us it cures this bug. Other browsers will take no notice of display:inline because it does not apply to floats.

All that’s left (graphically) for this section is to somehow add a rounded corner base to the bottom of the right column as seen in the original design. Its also worth noting that the whole page is capped off with 2 more rounded corners as well. There is no real way that we can find the bottom of the right column in order to place a rounded base there because the right column content is simply a float of content height. Therefore we will take a different approach and simply apply the whole base by using a background image in our footer element to complete the illusion.

The Footer

Slicing the whole three column base in one goes results in an image like this which is also shown in figure 11.

Figure 11

3 column base

The CSS is straight forward as follows:

PLAIN TEXT

CSS:

  1. #footer{

  2. width:975px;

  3. padding:20px 0 0 0;

  4. background:url(images/3col-base.jpg) no-repeat 0 0;

  5. clear:both;

  6. }

PLAIN TEXT

HTML:

  1. <div id=“footer”></div>

We can take a look at the layout so far and I have coloured the 3 columns red so we can check the positions are correct.

Figure 12:

Columns and footer

That looks just about right so the red colour can now be removed. The layout so far can be seen in this live example.

Things Left to do

We have completed the major structure of the site and will take a rest now

In the next part of the article we will add the content for each column along with the search form that we forgot to put in place. We also need to find a way to implement one last remaining structural graphical issue in that we will need to find a way of placing the watermark image that can be seen at the bottom of the outer columns. This is the image and is shown in Figure 13 also.

Figure 13:

flame image

This will prove quite tricky as the image is anchored to the bottom of columns 1 and 3 and at times will overlap the gradient background. However we will leave that to next time but you may wish to experiment and try for yourself.

There will also be some tidying up to do and once we have tested the result thoroughly in the browers we want to support we will remove the CSS from the Head and once again validate the CSS and HTML to avoid any unforseen errors

Pasar de Psd a Css en pocos pasos (1 de 2)

Saturday, August 16th, 2008

From PSD to CSS/HTML in Easy Steps - Part 1

This is the first in our 4 part series on how to take a PSD file and convert it into a fully CSS based html page. These are the first in a series of tutorials in which we build a fully working Photography site, all in clean Xhtml and CSS. All the code, templates and files are available for you to play with, and we encourage you to download and play with what is provided. The design template is licenced under the creative commons licence.

Lets get on with the tutorial!

One of the hardest parts of converting a PSD design into a well structured and semantic CSS/HTML layout is first knowing where to start. Although that may sound simplistic and obvious, it really does matter how you begin and that you build on strong foundations to start with. In this series of articles I will take you step by step through the conversion process and look at decisions that need to made on the way and how those decisions may need to adapt as things progress. The article will not address any specific graphic techniques (e.g. slicing and optimising) as this varies from paint package to package and is not the subject of the article. You will of course need to know how to do these things and I am assuming that you already have this basic knowledge.

For a starting point we are going to assume that you have just been handed a PSD by your clients graphic designer and asked to turn it into valid and workable CSS/HTML. (Obviously it would be better if you had input on the design before the “fait accomplis” was handed to you but for the purposes of the tutorial we will just accept that this is the case.)

Here is a smaller image of the layout we are going to eventually produce.

PSD Layout

Step 1

At first sight the layout looks quite straightforward but before we begin we should take a closer look at the elements and identify possible problem areas. At this early stage you may need to make important design decisions so you must have a clear idea of how the design can be achieved from the very start. If you identify areas that are impossible to create on a living web page or would cause to many browser issues then its best to locate them now and notify the client before you begin.

It is also worth mentioning at this point that you should have already agreed with your client exactly what work you are doing and exactly what they are paying for. If you don’t define the exact parameters of the job in hand you will find that the client will take advantage of this and ask for every possible addition under the sun and expect support forever all for a pittance.(Some clients are not like this but there are a number who will be very sharp.)

Fixed, Fluid or em based

With the disclaimers out of the way we can get on with the job in hand and look at initial issues and then break the layout down into more manageable chunks. The first question that needs to be asked is whether this is a fixed with layout or a fluid width layout where each column can stretch. Of course you should consult with your client on these matters but for the purposes of this first tutorial we will assume that it’s a fixed pixel width layout. Later on in the series we will explore how to convert the example to a fluid layout or an em based layout. But for the first article we will stick with pixels to make the process slightly easier to begin with.

My initial thoughts on looking at the PSD before even coding a line of html is that the designer has provided a lot of gradient and shadow effects in various places and also added rounded corners to some of the design elements. For example the background of the design has a vertical fade that fades from #282f27 - to #000000 over a 880 pixel range. That is no problem in itself in that we can repeat a vertical slice on the x-axis of the body while at the same time setting the body’s background color to the finishing color of the fade (#000). This will allow the layout to extend vertically forever without problem. The complications will arise in that the header elements have a a slight background fade placed around them that varies with the body’s fade.

We have two options here:

1) Create the fade around the element using PNG transparency for the fade so that the body’s faded background can show through the opaque PNG image. Although this is fine for most browsers there are severe issues with IE6 and under that won’t render the transparent PNG properly. We could use the proprietary alpha-image loader filter to compensate for IE5 and 5.5 if we have no other choice but that also comes with a number of associated problems and should only be used when there is no alternative.

2) Slice the elements background with the gradient shadow in place and match it up to the body’s gradient background. As the header elements are a fixed height then this should work fine. Of course should text be resized and the elements allowed to grow then the fade may become mismatched. However, I thinks that’s a small price to pay to keep the code simpler. Therefore this is the approach we will use for this method and if we find out later that its not good enough then we may have to think again.

Wire Frame

To roughly see what elements you need for the whole page you can create a wire-frame view of your site (either in your mind or just draw it on paper). Here is a quick mock up of the basic structure of our page.

Wire Frame

Although I am not going to build this wire frame for real it does give you a good visual clue as to what needs to be done and also provides some logical order to the proceedings. Some people will actually construct the wire frame version but I find this often gets in the way during development so we will do this my way and work our way through the page one element at a time and from the top down to the bottom.

Each area will present its own little problems but the basic structure can be seen to be a centred layout with three full width static horizontal sections followed by three columns that will need to be floated across the screen. The main part of the site will be the three floated columns and the big issues we will need to overcome are the three apparently equalising columns. This can be accommodated quite easily in our fixed with layout by using a repeating background image that creates the three columns automatically when we repeat it on a parent that is holding the 3 columns.

There will be additional issues to overcome in the main section because there are also vertical gradients and images aligned to the bottom to consider and we may need to adapt our design as we go. But for now it’s good enough to have realised this and considered what the options are. If at this point you believe something to be impossible as not all designs can be transcribed to the web you should contact your client and seek alternative strategies should the design need to be changed, Better to raise issues now rather that have the client say “it must be like this” when you have finished.

After identifying the main issues and ratifying any design changes its time to start on the real work and actually do some coding and slicing.

As mentioned above I like to work on one element at a time in a logical fashion so we tackle each of these issues in turn and the process will look like this.

1) Grab font sizes, font families and basic colors from the PSD and set up up CSS defaults for these including your favourite Reset CSS snippet. Also set up the default font-size structure that will allow for text to be resized in IE6 and under. In fact this is such a common process that you should already have a template set up so that you can start work straight away and allows you just to change the font family and colours and off you go.

2) Measure the layout so that we can create a wrapper for the content as the page needs to be centred so all content can be within the wrapper. However some designers will use a width on the body element instead of using an inner wrapper but this presents problems in older IE browsers and I recommend leaving the body alone. However it is an option if you want to be really minimalist.

I find that I am often giving PSDs of 800px width because the graphic designer has been told that it is for a 800 x 600 page and doesn’t realise that 800px is too wide for an 800px page due to chrome and scrollbar issues. The design would need to be about 760px wide (depending on browser) so as not to trigger a horizontal scrollbar. This is something you will get used to and need to look out for.

3) Start at the top and work down.

Working logically helps you break the job down into sections so that you can work on one thing at a time and plan the work accordingly. You always have to have an eye on what’s coming next but concentrating on one thing at a time will focus your efforts and give you a sense of accomplishment when each element is completed rather that having half finished elements everywhere.

In our PSD we have the navigation at the top followed by the logo and tag line. Then follows a header image with search box. Finally we have three columns and a small footer with copyright message.

I like to use logical names for the sections and although there is some debate about what to use for each element it does help if your naming convention allows for the fact that maybe your html will be arranged at a later date and that your element names still make sense. If for instance your left column is called #leftcol and the at a later date you switch it using CSS to be the right column then it could be very confusing. It’s better to use a more generic but functional name such as #sidebar1 for the left column and #sidebar2 for the right column or even #col1 and #col2. However you could move the sidebar to the middle and then it wouldn’t be a sidebar anymore so think carefully about your names but don’t go overboard with names that are so generic that you don’t know what they refer to.

For our layout we will use the following id’s:

#outer - hold all page content

#header - contains nav and other header elements such as logo and search.

#nav - main top navigation

#tagline - logo and tagline

#search - Search box and background image

#main - This is a wrapper that holds all three columns

#col1 - left column

#maincol - main centre column

#col3 - right column

#footer - Footer

For other internal elements we will use classes. Remember that IDs must be unique and can’t be used more than once per page.

Basic Structure

We now have enough to write our very basic html structure and set up some default stylesheets so that we are ready to roll.

HTML:

PLAIN TEXT

HTML:

 

 

  1. <!DOCTYPE html PUBLIC “-//W3C//DTD XHTML 1.0 Strict//EN” “http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd”>

  2. <html xmlns=”http://www.w3.org/1999/xhtml”>

  3. <head>

  4. <meta http-equiv=”Content-Typecontent=”text/html; charset=iso-8859-1″ />

  5. <title>Sanke Photography</title>

  6. <link href=”main.css” rel=”stylesheet” media=”screen, projection” type=”text/css” />

  7. <link href=”print.css” rel=”stylesheet” media=”print” type=”text/css” />

  8. <!–[if IE ]>

  9. <link href=”iecss.css” rel=”stylesheet” media=”screen,projection” type=”text/css” />

  10. <![endif]>

  11. </head>

  12. <body id=”home”>

  13. <div id=”outer”>

  14. <div id=”header”>

  15. <ul id=”nav”>

  16. <li><a href=”#”>About Us</a></li>

  17. <li><a href=”#”>Gallery</a></li>

  18. <li><a href=”#”>Contact Us</a></li>

  19. <li><a href=”#”>Events</a></li>

  20. <li><a href=”#”>News</a></li>

  21. </ul>

  22. <div id=”tagline”></div>

  23. <div id=”search”></div>

  24. </div>

  25. <div id=”main”>

  26. <div id=”col1″></div>

  27. <div id=”maincol”></div>

  28. <div id=”col2″></div>

  29. </div>

  30. </div>

  31. </body>

  32. </html>

Main CSS:

PLAIN TEXT

CSS:

 

 

  1. /* main CSS Document */

  2. /* general styling first */

  3. /* reset css styles individually instead of universal selector. */

  4. /* based on http://meyerweb.com/eric/thoughts/2007/05/01/reset-reloaded/ */

  5. html, body{

  6. margin: 0;

  7. padding: 0;

  8. font-weight: inherit;

  9. font-style: inherit;

  10. font-size: 100%;

  11. font-family: inherit;

  12. vertical-align: baseline;

  13. border-left:0;

  14. }

  15.  

  16. div, span, applet, object, iframe,

  17. h1, h2, h3, h4, h5, h6, p, blockquote, pre,

  18. a, abbr, acronym, address, big, cite, code,

  19. del, dfn, em, font, img, ins, kbd, q, s, samp,

  20. small, strike, sub, sup, tt, var,

  21. dl, dt, dd, ol, ul, li,

  22. fieldset, form, label, legend,

  23. table, caption, tbody, tfoot, thead, tr, th, td {

  24. margin: 0;

  25. padding: 0;

  26. border: 0;

  27. font-weight: inherit;

  28. font-style: inherit;

  29. font-size: 100%;

  30. font-family: inherit;