Sunday, 20 February 2011

CSS Layout: Positioning

Yesterday, during the Google Chrome Hackathon, I was trying to replace the text on a button with an image, for example, replacing "Go" in the button below with an arrow image.


I can certainly add a background image for the button, but the text will still be seen above the background. Due to the lack of time, I just deleted the text in the html file. However, I feel that replacing the text with an image is really a styling choice rather than semantic.

Today, I started to read the book "Pro CSS and HTML Design Patterns" to improve my css skills. It actually mentions about the Text Replacement design pattern in the first chapter. It requires the use of css layout positioning to achieve the effect.

First, a recap on the positioning models:
  • Position an element by setting position to something other than static.
  • Use left, right, top and bottom to change the default position.
  • You can use position: static to "unposition" an element.
position 
In flow 
Positioning
static
yes
according to the flow
relative 
ghost
relative to the flow position 
absolute 
no
offset from its nearest positioned ancestor     
fixed
no
screen coordinate space

Text Replacement

Replace "Go" with this image:

Result:


Method: (Taken from p209 of the book.)
HTML
 TEXT 
CSS
#UNIQUE-ID { 
  position:relative; 
  padding:0; 
  overflow:hidden;
  width:IMAGE_WIDTH;
  height:IMAGE_HEIGHT; 
}
#UNIQUE-ID span { 
  position:absolute; 
  left:0; 
  top:0; 
  margin:0;
  width:IMAGE_WIDTH;
  height:IMAGE_HEIGHT;
  background-image:url("FILE.EXT");
  background-repeat:no-repeat; 
}

Initially, when I was testing with this, I found that the Chrome browser includes the border width in the height and width of the content size. By inspecting the element, I found that box-sizing is set to border-box. By setting it back to content-box, it behaves normally.

No comments :

Post a Comment