A consistent pattern for CSS element positioning

I spend a lot of time switching between different languages and each has a slightly different pattern for element positioning. This often creates the need to pointlessly look up the rotation pattern for each language, which is no doubt a waste of time. To overcome this, I find that using the default pattern for a language consistently is key.

For example, CSS has a different pattern then XAML. However, by reusing CSS’ default pattern it makes our code easier to quickly scan and eliminates needless Google searches (sorry Google).

In CSS, the generic pattern is:

  1. top
  2. right
  3. bottom
  4. left

For example, if I set the padding on an element, then I can control the padding for each of the 4 items above as:

padding: 1px 2px 3px 4px;

That is:

  1. top = 1px
  2. right = 2px
  3. bottom = 3px
  4. left = 4px

So, when define the margin edge offset for positioned boxes, it is beneficial to follow this same pattern.

For example, if we have a positioned box such as <div class=”my_class”>, then we’ll follow CSS’ default pattern as follows:

<div class=”my_class>

Then in CSS:

.my_class {
    position: absolute;
    top: 0;
    right: 0;
    left: 0;
    bottom: 0;
}

As can be seen above, we specified the 4 margin edge offsets in the same order that CSS uses by default.

The end goal is to improve readability and to maintain consistency in how and where we specify our CSS. In a large web application, this consistency makes it easy to maintain our CSS by ensuring that we can quickly find a property without having to read every line in detail.

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s