SEO

March 31, 2011

There are three ways of centering a block:

There are three ways of centering a block:

  1. Centering with margins
  2. Centering with percentages
  3. Centering with absolute sizes.

The first method seems to work better for most.

There are multiple techniques for centering a block element; and the choice for the technique depends on whether you have the size set in percentages or in more absolute values.

Note: If an element fills the width of the screen along the axis you wish to center it along, then centering it will have no effect. Elements with display: block; default to width: auto; and fill the width of the screen, so set an explicit width on them.

Centering with auto-margins

This is a simple method of horizontal CSS centering that works well for block-level elements with either absolute or percentage widths.

It is based on the rule in the CSS2 Visual formatting model details stating that if both margin-left and margin-right are 'auto', their computed values are equal.

Centering an entire page's contents

The technique is particularly useful when you want to center an entire page's contents. Unlike the 'Centering with absolute sizes' method below, this method should prevent negative left margins from making the left-hand area of the element inaccessible in narrower browser windows.

Internet Explorer note: This centering does not work for Internet Explorer 5.5 or earlier but a workaround exists as IE will accept text-align: center; on a block level element and center it, even though this is incorrect.

Example

This code will center an entire page's contents when contained within a 'wrapper' div 500 pixels wide:

Uncommented example:

body { text-align: center; min-width: 500px; } #wrapper { text-align: left; width: 500px; margin-left: auto; margin-right: auto; }

Commented example:

body { text-align: center; /* MSIE 5 doesn't center based on auto left/right margins, but 'text-align:center' does center top-level divs: */ min-width: 500px; /* Specify a min-width for the body as wide as the 'wrapper' element itself. This prevents negative (i.e. inaccessible) left-margins in narrow browser windows when using Navigator 6+/Mozilla on Win32: */ }  see also: Centering: Auto-width Margins

Centering an absolutely positioned element

Auto-margins can center an absolutely positioned element inside its containing block. For this to work, you have to
  1. specify the offset properties (of opposite sides) with same values, i.e. by setting left:0; right:0; for horizontal centering and top:0; bottom:0; for vertical centering,
  2. set dimensions along the axis you want to center along,
  3. enable auto-margins along the axis you want to center along.
Internet Explorer note: IE can not relate absolutely positioned elements to opposite sides of containing block, so only one of the offset properties is used. This brings the element out of balance and renders auto-margins useless. A workaround is use relative positioning for the element to be centered and wrap it with an absolutely positioned element with top, left and right set to 0.

Example

These CSS definitions will horizontally center a DIV of class center inside its container DIV of class container on most browsers except Internet Explorer.
.container { position: relative; /* make this a containing block! */ border: 1px dotted red; /* mark this element visually prominent */ } .center { position: absolute; /* take element out of the normal page flow! */ top: 10px; /* position the element vertically using top or bottom and define width as you like:*/ width: 50%; left: 0; /* set left and right to the same value! */ right: 0; margin-left: auto; /* adding auto-margins left and right will center the element horizontally!*/ margin-right: auto; background:red; /* mark this element visually prominent */ }

A Mac/IE Bug centering tables

If you are trying to center a table using this method, keep in mind that you must use the longhand margin properties (e.g. margin-left, as shown above) if you want it to work in Mac/IE. The shorthand margin: 0 auto; will work for other blocks in Mac/IE, but not for tables. Table centering using CSS or HTML

Centering with percentages

This is the simplest centering method. The following example is for horizontal centering, but you can apply the same logic to the vertical centering. You know the width of the block you want to center; say 40%. If you want to center this block, you need to position this block half the space that's left from the edges, which means you have to move the block (100%-40%)/2 = 60%/2 = 30% from the left (or the right if you prefer).

Example

Centering a block with a width of 60% and a height of 30%:
.centerblock { position: absolute; width: 60%; height: 30%; left: 20%; top: 35%; }

Centering with absolute sizes

This is a little bit more sophisticated. I'll be explaining it for horizontal centering, but again, it's the same for the vertical centering. You need to have a fixed width for your block in .g. px; say 300px. Now you move this box 50% to the left, so that the left side of the box will be in the center. The trick with this centering method is that you use negative margin's to 'move the box' in the opposite direction. You move the block half the width of the block this way. In this case this means you need to set margin-left to -(300px/2) = -150px;

Example

Of course, this trick will get an example too. Let's assume you want to center a box width the following dimensions; height: 350px; width: 280px;.
.centerblockabsolute { position: absolute; width: 280px; height: 350px; left: 50%; top: 50%; margin-left: -140px; margin-top: -175px; }

When you don't know the width

If you want to "shrink wrap" (to add borders or something like that) an image (or other block element) without knowledge of its width in the CSS, and you also have small captions, and then you want center the whole thing. Instead of using a float, you could use a container with display: table/table-cell;. This gives you the shrink-wrap effect and can be horizontally centered with auto margins. It doesn't work in IE (neither on Windows nor Mac.) For these you could try display: inline-block with conditional comments, which should give the shrink wrap effect, and can be centered inside a container with text-align: center (see previous section). This method is discussed here: http://www.solstice.co.il/2008-02-26/horizontally_centering_content_with_dynamic_width_in_css If you are not happy with display: inline-block or display: table/table-cell (not supported by all browsers) you can center a left-floated block (such as a menu) by relative positioning. This method is discussed here: http://matthewjamestaylor.com/blog/beautiful-css-centered-menus-no-hacks-full-cross-browser-support Alternatively, you can use Javascript to do the same thing, only a bit less elegant: In IE ( Java Script  active) you can use Dynamic Properties, provided that you have two containers (one outer and one that is centered):
.centerblock { margin-left: expression (this.offsetWidth < this.parentNode.offsetWidth ? parseInt ((this.parentNode.offsetWidth - this.offsetWidth)/2)+"px":"0");}
The display: table; trick is known to work in Opera, Safari and Mozilla/Firefox. (courtesy of CSS-Discuss) Another drawback is that any floated DIVs contained within the display:table block will collapse into each other. (unless someone has a fix?)

Vertical Centering

Vertical Centering of element of Known height

http://www.hicksdesign.co.uk/journal/vertical--horizontal-centering-2 http://vmalek.murphy.cz/ http://www.student.oulu.fi/~laurirai/www/css/middle/ http://phrogz.net/CSS/vertical-align/index.html http://phrogz.net/CSS/valign_in_body/content.html http://stilbuero.de/demo/vertical_centering.html http://d-graff.de/fricca/center.html

Vertical Centering of element of Unknown height

http://www.jakpsatweb.cz/css/css-vertical-center-solution.html http://brunildo.org/test/shrink_center_4.html http://www.sunburnt.com.au/publications/design/center-multiple-lines-with-css

css basic examples

http://www.csscentering.com

Code needed to make <input type="search"> look exactly like type="text".

input[type="search"] { -webkit-appearance: textfield; outline-offset: -2px; }  input[type="search"]::-webkit-search-decoration, input[type="search"]::-webkit-search-cancel-button, input[type="search"]::-webkit-search-results-button, input[type="search"]::-webkit-search-results-decoration { display: none; }

More on the topic.

Stop writing single-line CSS

September 28, 2010

Writing single-line CSS is not a matter of preference.

  • Adding ending slashes in HTML5 because you're switching from XHTML is a preference.
  • Using MooTools over jQuery is a preference.
  • Writing curly braces in new lines is a preference.

Single-line CSS is not your preference - it's a shitty way to code, debug and optimize and I'm gonna prove it to you right now.

Your arguments go like this:

It's syntactically valid!

Just because you can skip whitespace in CSS, doesn't mean you should. Sure, you are a smart cookie and you can read it very quickly, breaking long chains of well-known properties and their values in real time. CSS is rather easy.

Let's switch gears for a while. Look at this JavaScript:

for (var ,i=0;i<10;i++){l=(i % 2)?'even':'odd';}

I hope one day you will have to work with stuff like this so you can understand that unreadable code is always bad code, even if it executes.

It's quicker to write!

Probably, but the quality suffers.

I have seen many stylesheets in countless projects and those with single-line rules are almost always full of redundant selectors and redeclared properties. I'm talking about this:

.footer li h3 { margin: 0 0 6px; font-weight: bold; display: inline; color: #e92e2e; } .footer li h3 a { font-weight: normal; font-size: 1em; color: #e92e2e; }

Color property should be declared like this:

.footer li h3, .footer li h3 a { color: #e92e2e; } .footer li h3…

When you write CSS, you need to constantly optimize. You have to reorder selectors, move properties around and shrink rulesets while new functionality is being added. You can't just move to the bottom of file, dump and overwrite.

Single-line CSS is quicker to write when you stop caring about stuff you already coded. If you don't remember what you code, you will end up with repetitions and bloat.

I can see much more on the screen!

Only vertically. Horizontally you have many, many problems:

  • Long rulesets are being wrapped - nice column of selectors stops being nice
  • With wrapping disabled, you are limited by the viewport - code bloat increases, as you won't remember about invisible code
  • Even if you refactor and move code around, you end up decreasing readability.

All of this doesn't really matter, though. Tell me: why on Earth would you force a coding style on your peers to compensate for your shitty editor?

There are many text editors and IDEs that will take care about screen estate. Editors that can collapse unused rules or sections. Editors with project inspectors, allowing you to jump to particular selector. Or those that have powerful, tweakable capabilities.

It has smaller size!

Really. You want to compress front-end code by hand, while developing the site / application. Do you omit spaces after periods in sentences too?

Learn what minimization means and how you can do it automatically in production environment. If you have no idea how to do it yourself, your back-end guy or sysadmin will help. And if you're a one-man-army, just Google around and use some online tools at the very end. On a copy.

If you want, you can use a reformatter. You hipster.

It will probably be the first thing I do when I must edit your code. Make no mistake - it's not a solution, this is me fixing your shit. You don't ask people to use Tidy on your HTML before making back-end templates, do you?

I just like it.

First, you should read about lizard brain. Second, realize that your coding style will interfere with efficiency of your co-workers. Even if you end up with someone who also writes single-line CSS, her style might be different. She may be using OOCSS approach (however strange that would be for such a messy person) and she will curse you under her breath for your screen-long selectors.

You may indeed like it, but if you ever need to work with someone else and produce high-quality code, this is not how you do it. In team environment single-line CSS will be the first reason for pouring coffee on your new MacBook.

If you're a lone hunter, do what you like. Browse 4chan, smoke, have 5 espressos a day, whatever. But don't tell me I should not criticize you for writing single-line CSS. If I care enough to do this, you probably deserve to be better than you are right now.

Accessible image replacement with CSS3

July 4, 2010

Image replacement is as old as CSS tips and tricks posted online. Here's a list of available techniques. Recently I've become particularly interested in the Gilder/Levin method. It uses additional span element, positioned over the parent. This span then gets background-image treatment, covering underlying text.

I normally use it like this:

<h1>Futurama <span></span></h1>  h1 { position: relative; width: 256px; height: 133px; }  h1 span { position: absolute; top: 0; left: 0; width: 100%; height: 100%; background: url("image.png") no-repeat; }

Why do I bother? This is the only (sane) method allowing images to be disabled or not downloaded at all. And why would I care about this?

  • I want to provide alternative way to access all content on the page, full stop. This is supposed to be a replacement, not obliteration.
  • There is a small lag between rendering DOM element and downloading the image. Browsers are so fast these days that it can happen even on broadband.

It's all good and I use it all the time for logo elements (headings usually get @font-face anyway). The only thing that bugs me is that additional span element. Today I learned how to get rid of it.

Note: In my daily work I support only modern browsers (including IE8), so if you need to support earlier versions of Firefox (3.0) or IE 4.0, stop reading. ;)

Code looks like this:

<h1>Futurama</h1>  h1 { position: relative; width: 256px; height: 133px; }  h1:after { content: url("image.png"); position: absolute; left: 0; top: 0; }
#outer { height : 400px; overflow : hidden; position : relative; width : 100%; }#outer[id] { display : table; position : static; }#middle { position : absolute; top : 50%; width : 100%; text-align : center; }#middle[id] { display : table-cell; vertical-align : middle; position : static; }#inner { position : relative; top : -50%; text-align : left; width : 200px; margin-left : auto; margin-right : auto; }div.greenBorder { border : 1px solid green }#container { width : 960px; margin : 0 auto; }.greenBorder { border : 1px solid green }#container { width : 960px; margin : 0 auto; }

Valid CSS information

div.c2 {
background-color : ivory;
border : 1px solid green;
border : 1px solid green;
height : 400px;
margin-left : auto;
margin-right : auto;
overflow : hidden;
position : relative;
position : relative;
text-align : left;
top : -50%;
width : 100%;
width : 200px;
}
img.c1 {
border : 0;
width : 88px;
height : 31px;
}

 

Valid CSS!

Please view source for details.