Showing angular expression at page load

angularIn my application I want to show a table data. I am showing a loading icon at first. At that time table will hidden. after data load that table will display. its working good. But some times some browsers showing angular expressions in table at page. After a 1/4 sec it will gone. But it shown 1/4 sec!!. I tried ng-show, ng-if, add a class,etc. everything failed. It is not fixed permanently. After that I tried with ng-cloak. It works!

I added the below code in my css file, and add a class to my table element.

CSS

[ng\:cloak], [ng-cloak], [data-ng-cloak], [x-ng-cloak], .ng-cloak, .x-ng-cloak {
display: none !important;
}

Html

<table  class="ng-cloak">
....</table>

Animation Using CSS Transforms

The examples on this page will work properly in Safari, Chrome and
Opera. In Firefox prior to version 4 you will see the transforms, but
without any animation. Transformation effects also work now in Internet
Explorer 9 using the -ms- vendor prefix.The implementation of animation in CSS involves setting up a transformation to take place in response to a
mouseover or other event. Then, rather than applying the effect
instantly, we assign a transition timing
function
which applies the transformation/s over a set time
period.Firefox and Opera now support these transforms with an almost
identical syntax – just replace -webkit with -moz or
-o in the examples below and you will see the same effects.
And you can use -ms to enable transformation effects for
IE9.

1. Introducing CSS Transformations

The effect of a CSS Transform is to modify the appearance of an
element in the browser by translation, rotation or other means. When
defined in a style sheet transformations are applied before the page is
rendered, so you don’t actually see any animations taking place.
Transforms can also be applied as a mouseover or similar effect
which you can see in the next section.

Apple’s proposal for CSS Transformations calls for
the ability to change the perspective and work in three dimensions, but
that’s some way away yet. Even the features demonstrated here won’t
appear in other browsers until they’re approved by the standards body
who are still quibbling over CSS3 modules.

Below we’ve placed four identical DIV’s styled as a 100 x 60 pixel
box with a 2 pixel border. Subsequently, each element has been
transformed in some way using the -webkit-transform property as
follows:

box 1 Translated to the right: -webkit-transform: translate(3em,0);
box 2 Rotated 30 degrees with the clock: -webkit-transform: rotate(30deg);
box 3 Translated to the left and down: -webkit-transform: translate(-3em,1em);
box 4 Scaled to twice its original size: -webkit-transform: scale(2);
box 1
box 2
box 3
box 4

Without the translations, and the red border on the second box, you
would see just four identical boxes labelled one through four. What you
see in supported browsers (Safari, Chrome, Firefox, Opera), however,
will be more like this:

Of note is the fact that the text is still selectable in transformed
elements, even when rotated, and that scaling an element affects other
properties including border widths and font sizes and not just the
dimensions.

2. Animating your Transforms

While CSS Transformation in itself is a powerful tool for developers
(though I shudder to think what would happen if it was more widely
available), the ability to animate the same effects using
-webkit-transition is far more exciting. Move your mouse over
the following four boxes for a demonstration:

box 1
box 2
box 3
box 4

What you see above is the four boxes from the previous section, in
their default states. When you mouseover any of the boxes, however, the
CSS transformation is applied as a one second animation. When the mouse
moves away the animation is reversed, taking each box back to its
starting position and state. And we achieve this without using
JavaScript – only HTML and CSS!

If you think that’s cool, realise that CSS Animation can be applied
not just to the transforms, but also to other CSS properties including:
opacity, colour and a bunch of other properties.

In the next example the box on the left begins as small and green
with square corners, while the one on the right is larger, with a red
border and rounded corners. Hovering over either of the boxes will
trigger an animation that makes box 1 take on the appearance of box 2
and vice versa.

box 1
box 2

Again, we’re still only using HTML and CSS to make this happen.
Without CSS Transforms the two boxes will still change their
border-color, and possibly also the border-radius, but
it happens immediately rather than as a one second animation.

For more advanced examples you can read our new article on using JavaScript to trigger the
animation
.

3. Multiple Transforms on one element

To apply more than one transformation to a single element simply list
them one after another separated by spaces. The submenu for example at
the top right of this page has the following styles:

<style type="text/css">

#submenu {
background-color: #eee;
-webkit-transition: all 1s ease-in-out;
-moz-transition: all 1s ease-in-out;
-o-transition: all 1s ease-in-out;
-ms-transition: all 1s ease-in-out;
transition: all 1s ease-in-out;
}
#submenu:hover {
background-color: #fc3;
-webkit-transform: rotate(360deg) scale(2);
-moz-transform: rotate(360deg) scale(2);
-o-transform: rotate(360deg) scale(2);
-ms-transform: rotate(360deg) scale(2);
transform: rotate(360deg) scale(2);
}

</style>

This means that when you hover over the submenu, it will change
colour, rotate and double in size over a period of one second as shown
here:

<=>

These effects are now available in the latest public release of
Safari, so in principle all OSX users will be able to see these effects.
Whether it’s a good idea to add them to your website I’ll leave up to
you.

Update: Thanks to misterbisson those without WebKit can now see a
screencast of the menu animation:

4. Animations in action

Now here’s another example of the kind of fun we can have in
combining different effects into single animation. Perhaps you can
already work out what’s going to happen based on the CSS?

<style type="text/css">

#outerspace {
position: relative;
height: 400px;
background: #0c0440 url(/images/outerspace.jpg);
}
div.rocket {
position: absolute;
bottom: 10px;
left: 20px;
-webkit-transition: all 3s ease-in;
-moz-transition: all 3s ease-in;
-o-transition: all 3s ease-in;
-ms-transition: all 3s ease-in;
transition: all 3s ease-in;
}
div.rocket img {
-webkit-transition: all 2s ease-in-out;
-moz-transition: all 2s ease-in-out;
-o-transition: all 2s ease-in-out;
-ms-transition: all 2s ease-in-out;
transition: all 2s ease-in-out;
}
#outerspace:hover div.rocket {
-webkit-transform: translate(540px,-200px);
-moz-transform: translate(540px,-200px);
-o-transform: translate(540px,-200px);
-ms-transform: translate(540px,-200px);
transition: all 2s ease-in-out;
}
#outerspace:hover div.rocket img {
-webkit-transform: rotate(70deg);
-moz-transform: rotate(70deg);
-o-transform: rotate(70deg);
-ms-transform: rotate(70deg);
transform: rotate(70deg);
}

</style>

rocket animation
.rocket

#outerspace

If you’re using Safari 3 you may notice some problems with the
animation, particularly when it reverses after you move the mouse away,
but in the latest version of WebKit it’s already much smoother. Also
the animation in Opera is a bit erratic, with not all the elements being
animated.

The dotted outline that appears during the animation shows the
placement of the DIV containing the rocket image. This DIV translates
across the screen while the image inside is rotated. Simple!

For the browser-impaired what’s happening is that when you move the
mouse over the space background, the rocket translates from the bottom
left to the top right over a period of 3 seconds (translate())
and also rotates 70 degrees in a clockwise direction over the first 2
seconds (rotate()). The effect is rudimentary, but shows the
potentional.

To have more control over the animation paths and timing, you can
set up WebKit Keyframes. They also
allow the animations to run automatically rather than in response to
mouse events.

5. Multiple timing functions

#stage

#block

In this example we are applying four different transitions using four
different timing functions.

When you :hover over the area to the right the blue box will
spin, change color from red to blue and move from the top left of the
containing box to the bottom right over two seconds.

The first thing you will notice is that that the movement of the box
appears to be curved rather than straight. That’s because we’ve used
the ease-out timing
function
for the horizontal translation and ease-in for
the vertical.

The other feature is that the colour change from blue to red takes
place over the first second of the two section transition, followed by
the rotation which takes place over the second second.

The trick to this is that instead of defining the
-webkit-transition as a single property, you can break it up
into component parts. We’ve also made use of
-webkit-transition-delay which allows you to set the starting
point of different effects.

Here are the relevant CSS statements:

#block {
...
background: blue;
...
-webkit-transition-property: left, top, background, -webkit-transform;
-webkit-transition-duration: 2s, 2s, 1s, 1s;
-webkit-transition-timing-function: ease-out, ease-in, linear, ease-in-out;
-webkit-transition-delay: 0, 0, 0, 1s;
...
}
#stage:hover #block {
left: 100px;
top: 100px;
background: red;
-webkit-transform: rotate(360deg);
}

The rules affecting the background colour transition have been
highlighted.

Firefox does not appear to support the
transition-delay option
requires units to be specified even
for zero values in -moz-transition-delay, so 0s, 0s, 0s, 1s will work for the example above.

6. Hover over one element to affect another

A couple of people have asked about triggering animations in
relation to a click or hover event elsewhere on the page. With
JavaScript this can be done by using an event handler to set or change
the className of the element to be animated, and to have a
transformation or keyframes associated with the new class.

Using CSS there are some options for targeting related elements.
These involve selectors such as the > (child), +
(adjacent sibling) and ~ (general sibling) combinators.

The preceding examples all required a direct hover event
either on the element itself or on its container, wheras in this example
the blue box is animated only when you hover over its sibing, the red
box:

#box1
#box2

#stage2

The relevant CSS code is as follows. Note that we are using the
+ adjacent sibling combinator to target #box2 when
#box1 experiences a hover event. The ~ combinator may
be more flexible in letting you target elements that are further away
from the triggering element (some examples).

#box2 {
position: absolute;
left: 120px;
...
background: blue;
...
}
#box1:hover + #box2 {
-webkit-transform: rotate(360deg);
-moz-transform: rotate(360deg);
-o-transform: rotate(360deg);
-ms-transform: rotate(360deg);
transform: rotate(360deg);
left: 627px;
background: yellow;
}

Of course we can still animate the first box at the same time as
targeting it’s sibling or siblings:

#box3
#box4

#stage3

Just be sure not to move the hovered element out from under the
pointer or the animation will stop/reverse.

These examples work more or less as intended in WebKit (Safari,
Chrome), Firefox and Opera. They may also work in IE10 or higher – if
anyone can confirm that please let us know.

7. References

Using Calc() Function

As mentioned above, we can use calc() to determine lengths like widthheightmargin,paddingfont-size, etc. To measure, we can use Mathematical expressions: Addition, Subtraction, Division and Multiplication.

For an example, let’s say, we have three <div> within a wrapper, as shown below.

  1. <div class=”col one”>A</div>
  2. <div class=”col two”>B</div>
  3. <div class=”col three”>C</div>

With calc() function, we can easily set these <div> into columns with equal width this way.

 

  1. .wrapper .col {
  2.     width: calc(100% / 3);
  3.     padding: 0 10px;
  4. }

The following Mathematical operation calc(100% / 3); divides 100% of the parent width by three and here is how it turns out in the browsers. The three <div> are having equal width.

CSS Units

Unit takes an important role for measuring and building things like a house, a bridge or a tower, and building a website is not an exception. There are a number of methods of measurements used on the Web, specifically in CSS, namely Pixel, EM and Percentage.

In this post, we are going to run through these units to get further insight into these units of measurements.

PX

Pixel is a fixed unit measurement and the smallest unit on screen measurement but don’t confuse this with the Pixel that defines screen resolution. The Pixel in CSS has nothing to do with the screen resolution. When we try viewing a web page fixed at 1024px width say on a tablet with 1024px by 480px screen resolution, the web page will not fit in the screen.

I’ve been experiencing this issue in the past and found out that the Pixel in CSS is actually not a linear unit – it is in fact a radial measurement. Basically, the Pixel in CSS measures the length of the display area instead of the screen resolution, so the 1024px screen resolution does not mean that the screen is also 1024px of the length.

More On PX

I’m not an expert on the technicalities in this matter but if you know Trigonometry, and want to find out more, check out the following explanation from Sean B. PlamerCSS px is an Angular Measurement.

Finding The Display Area

So, how do we find the actual display area of a device? Luckily, there is a handy special calculator toroughly estimate the display area in format of Pixel, CM to PX. We simply need the length of the device in cm and the PPI (Point Per Inch) / DPI (Dot Per Inch) which you can get these from the device box. With this, it turns out that the tablet I used is merely 953pxin length.

Recommended Reading: Pixel Identity Crisis

Pixels Font Size In Photoshop

When working on Photoshop, we will find that the font size is by default set to Pt (Points). The Pt unit is ideal for print styles. To not confuse this with px when we are translating it to Web documents, we can change the units from the following menu: Edit > Preferences > Units and Rulers.

There, you get a window option as shown in this screenshot below. Choose ‘pixels’ for the Type unit.

And, we have px for the font size.

EM

EM is a relative measurement. In CSS, EM refers to the multiplication of the default font size from the device or the document itself, that is why I personally word EM as EMphasize, but of course don’t take my word for it.

Here is an example; let’s say in a document, the font size is assigned for is 16px1em is equal to16px2em is equal to 32px and so on. Although EM is traditionally used for font sizing and in fact it is the standard unit used in browser styles for measuring font size, we can also used EM to define an element’s length.

The only constraint when working with EM unit is it is not quite intuitive, but there are two practical ways we can handle this. First, we can use this calculator, PX to EM; it’s a handy calculator that I use often.

Another way is to set the document pixel base to 10px, so we can calculate it more easily; for instance setting 15px at 1.5em. Well, I hope you get the basic idea with this example.

Percentage

It is more straightforward with percentage, which measures relatively to the parent length. When the parent width is 800px then 50% would become 400px. In recent years, as Responsive Designstarts becoming the web design standard, percentage unit is adapted more frequently in the wild.

Alright, let’s take a look at the following example; this code below defines .container and .mainclass selector with 60% for the width, but these classes refer to different parents thus they generate different lengths. The .container will take 60% of the browser viewport width, whilst the .main will take .container width as its direct parent.

  1. .container {
  2.     width: 60%;
  3.     margin: 100px auto;
  4.     background-color: #eaeaea;
  5.     padding: 1%;
  6.     height: 250px;
  7.     font-family: Arial;
  8.     text-align: center;
  9. }
  10. .main, .aside {
  11.     line-height: 253px;
  12. }
  13. .main {
  14.     width: 60%;
  15.     height: 100%;
  16.     float: left;
  17.     background-color: #ccc;
  18. }
  19. .aside {
  20.     width: 40%;
  21.     height: 100%;
  22.     background-color: #aaa;
  23.     float: left;
  24. }

Thus, it will give us the following nice result:

As percentage is also a relative unit, so it has a similar constraint like the EM unit as well. It is not obvious how much a percentage 15px is of 500px? This generally happens when we translate pxunit from the design stage to web document in many cases. There are two ways we can take to this matter, either we do it traditionally with a calculator or if you are comfortable with using CSS Pre-processor, you can utilize the percentage() function from Sass.

Recommended Reading: Responsive Web Design in Sass Part 1: Fluid Layouts and Fluid Images.

Final Thought

There are many discussions on the best practices of using units in web design. But ideally the PX unit should be used when the properties generally need to be precise e.g. the border-radius andbox-shadow horizontal or vertical offset, whilst for the EM unit as suggested by W3C is better used for font sizing. Percentage is the ideal unit to use on responsive layouts.

Share your thoughts on the subject.

How CSS Positioning Works

Undoubtedly, the position property is one of the most useful tools that designers have in their CSS toolbox. However, there are a few concepts about positioning that might baffle beginners.

First, what is positioning?

When your browser opens a webpage, it starts rendering elements (divs, paragraphs, headings etc.) in the order they appear in the HTML markup of the page. Positioning is a natural way of organizing how the elements are displayed and an easy resolution to situations like overlaps. There are four types of positioning: staticrelativeabsolute and fixed.

Elements are statically positioned by default

The default positioning, which is implicitly applied to every element on the page, is static. Static positioning means that every element is positioned in the natural order it is added to the page. Block elements are displayed under other block elements, and inline elements are displayed next to other inline elements.

Relative positioning

Setting the positioning to relative does not by itself produce any noticeable difference in the way the element is displayed on the page. But you can now move it from its normal position with the topleft,bottom and right CSS properties. This comes really handy when dealing with situations in which you need to offset an element, but not anchor it to a specified position on the page.

.relativeDiv{

	/*
		Moving the div to the top-left
		from where it would normally show:
	 */

	position:relative;
	top:-50px;
	left:-100px;
}

Fixed positioning

Adding position:fixed to the CSS declarations of an element, positions it in relation to the browser window. This allows you to display toolbars, buttons or navigation menus, which are anchored at a fixed position and scroll with the page.

.fixedDiv{

	/*
		Fixing the div 20 px from the bottom
		of the browser window:
	 */

	position:fixed;
	right:20px;
	bottom:20px;
}

Probably the only drawback is that this positioning is not supported in older browsers like IE6, if you can’t afford the luxury of dropping support for these.

Absolute positioning

An absolutely positioned element is displayed on the page in relation to the document, or a parent element with a positioning different from static. This way, using the topleftbottom and right CSS properties, you can specify an exact position. This also gives you the ability to center divs horizontally and vertically, which we discussed in the “Centering a Div Both Horizontally And Vertically” MicroTut.

.parentDiv{

	/* Absolute and Fixed positioning would work as well: */

	position:relative;
}
.absoluteDiv{

	/*
		Displaying the div 50px from the right and 90px from
		the top of its parent because of the explicit positioning
	 */

	position:absolute;
	right:50px;
	top:90px;
}

The benefits

Using these positioning properties you can achieve all kinds of advanced page layouts, which will bring your designs to the next level. In conjunction with the z-index property, you can change the default overlay rules that apply to elements (elements which appear later in the code are shown above the previous ones).

What is the coolest design you’ve done with the positioning properties? Brag in the comment section below.

30 Useful CSS Snippets for Developers

CSS is certainly the most used and powerful web language that we use. While HTML is responsible for the page structure, it can be unpredictable across all new and old browsers. This is where the CSS comes in to help us solve those problems, but in the same time we can be more creative and style our webpage the way we want. No matter if we code a basic CSS website or a WordPress Theme, there’s no life without CSS. Below is a great list of 30 CSS Snippets and I’m sure whether you are an experienced web designer or you just making your way in, they are all well worth checking out.

Css Reset

html, body, div, span, applet, object, iframe,
h1, h2, h3, h4, h5, h6, p, blockquote, pre,
a, abbr, acronym, address, big, cite, code,
del, dfn, em, font, img, ins, kbd, q, s, samp,
small, strike, strong, sub, sup, tt, var,
b, u, i, center,
dl, dt, dd, ol, ul, li,
fieldset, form, label, legend,
table, caption, tbody, tfoot, thead, tr, th, td {
	margin: 0;
	padding: 0;
	border: 0;
	outline: 0;
	font-size: 100%;
	vertical-align: baseline;
	background: transparent;
}

body {
	line-height: 1;
}

ol, ul {
	list-style: none;
}

blockquote, q {
	quotes: none;
}

blockquote:before, blockquote:after,
q:before, q:after {
	content: '';
	content: none;
}

/* remember to define focus styles! */
:focus {
	outline: 0;
}

/* remember to highlight inserts somehow! */
ins {
	text-decoration: none;
}

del {
	text-decoration: line-through;
}

/* tables still need 'cellspacing="0"' in the markup */
table {
	border-collapse: collapse;
	border-spacing: 0;
}

Style links depending on file format

/* external links */
a[href^="http://"]{
	padding-right: 20px;
	background: url(external.gif) no-repeat center right;
}

/* emails */
a[href^="mailto:"]{
	padding-right: 20px;
	background: url(email.png) no-repeat center right;
}

/* pdfs */
a[href$=".pdf"]{
	padding-right: 20px;
	background: url(pdf.png) no-repeat center right;
}

 

Remove textarea scrollbar in IE

textarea{
	overflow:auto;
}

Browser specific hacks

/* IE 6 */
* html .yourclass { }

/* IE 7 */
*+html .yourclass{ }

/* IE 7 and modern browsers */
html>body .yourclass { }

/* Modern browsers (not IE 7) */
html>/**/body .yourclass { }

/* Opera 9.27 and below */
html:first-child .yourclass { }

/* Safari */
html[xmlns*=""] body:last-child .yourclass { }

/* Safari 3+, Chrome 1+, Opera 9+, Fx 3.5+ */
body:nth-of-type(1) .yourclass { }

/* Safari 3+, Chrome 1+, Opera 9+, Fx 3.5+ */
body:first-of-type .yourclass {  }

/* Safari 3+, Chrome 1+ */
@media screen and (-webkit-min-device-pixel-ratio:0) {
 .yourclass  {  }
}

Clearfix

 
.clearfix:after {
	visibility: hidden;
	display: block;
	font-size: 0;
	content: " ";
	clear: both;
	height: 0;
}

.clearfix { display: inline-block; }

/* start commented backslash hack \*/
* html .clearfix { height: 1%; }
.clearfix { display: block; }
/* close commented backslash hack */

Center the website

       .wrapper { 
 	width:960px;
	margin:0 auto;
  }

Rounded corners – border-radius

.round{
   -moz-border-radius: 10px;
   -webkit-border-radius: 10px;
   border-radius: 10px; /* future proofing */
   -khtml-border-radius: 10px; /* for old Konqueror browsers */
}

Add a drop cap

p:first-letter{
   display:block;
   margin:5px 0 0 5px;
   float:left;
   color:#000;
   font-size:60px;
   font-family:Georgia;
}

Using @fontface

@font-face {
    font-family: 'MyFontFamily';
    src: url('myfont-webfont.eot?') format('eot'),
         url('myfont-webfont.woff') format('woff'),
         url('myfont-webfont.ttf')  format('truetype'),
         url('myfont-webfont.svg#svgFontName') format('svg');
    }

Cross Browser Inline-Block

li {
        width: 200px;
        min-height: 250px;
        border: 1px solid #000;
        display: -moz-inline-stack;
        display: inline-block;
        vertical-align: top;
        margin: 5px;
        zoom: 1;
        *display: inline;
        _height: 250px;
}

Fixed Footer

#footer {
   position:fixed;
   left:0px;
   bottom:0px;
   height:30px;
   width:100%;
   background:#999;
}

/* IE 6 */
* html #footer {
   position:absolute;
   top:expression((0-(footer.offsetHeight)+(document.documentElement.clientHeight ? document.documentElement.clientHeight : document.body.clientHeight)+(ignoreMe = document.documentElement.scrollTop ? document.documentElement.scrollTop : document.body.scrollTop))+'px');
}

Changing the size of your content area

#content {
    width: 100%;
    margin: 0;
    float: none;
}

CSS3 Media Queries

/* Smartphones (portrait and landscape) ----------- */
@media only screen
and (min-device-width : 320px)
and (max-device-width : 480px) {
/* Styles */
}

/* Smartphones (landscape) ----------- */
@media only screen
and (min-width : 321px) {
/* Styles */
}

/* Smartphones (portrait) ----------- */
@media only screen
and (max-width : 320px) {
/* Styles */
}

/* iPads (portrait and landscape) ----------- */
@media only screen
and (min-device-width : 768px)
and (max-device-width : 1024px) {
/* Styles */
}

/* iPads (landscape) ----------- */
@media only screen
and (min-device-width : 768px)
and (max-device-width : 1024px)
and (orientation : landscape) {
/* Styles */
}

/* iPads (portrait) ----------- */
@media only screen
and (min-device-width : 768px)
and (max-device-width : 1024px)
and (orientation : portrait) {
/* Styles */
}

/* Desktops and laptops ----------- */
@media only screen
and (min-width : 1224px) {
/* Styles */
}

/* Large screens ----------- */
@media only screen
and (min-width : 1824px) {
/* Styles */
}

/* iPhone 4 ----------- */
@media
only screen and (-webkit-min-device-pixel-ratio : 1.5),
only screen and (min-device-pixel-ratio : 1.5) {
/* Styles */
}

Multiple Background Images

#multiple-images {
   background: url(image_1.png) top left no-repeat,
   url(image_2.png) bottom left no-repeat,
   url(image_3.png) bottom right no-repeat;
}

Multiple Columns

#columns-3 {
   text-align: justify;
   -moz-column-count: 3;
   -moz-column-gap: 12px;
   -moz-column-rule: 1px solid #c4c8cc;
   -webkit-column-count: 3;
   -webkit-column-gap: 12px;
   -webkit-column-rule: 1px solid #c4c8cc;
}

Min-height in IE

.box {
   min-height:500px;
   height:auto !important;
   height:500px;
}

Highlight Text Selection

::selection {
   color: #000000;
   background-color: #FF0000;
}

::-moz-selection {
   color: #000000;
   background: #FF0000;
}

Box Shadow

box-shadow: 0px 3px 3px rgba(0,0,0,0.2);
-moz-box-shadow: 0px 3px 3px rgba(0,0,0,0.2);
-webkit-box-shadow: 0px 3px 3px rgba(0,0,0,0.2);

Placeholder Text Styling

::-webkit-input-placeholder { color: #ccc; font-style:italic }
:-moz-placeholder           { color: #ccc; font-style:italic }

CSS3 3D Text

h1 {
  text-shadow: 0 1px 0 #ccc,
               0 2px 0 #c9c9c9,
               0 3px 0 #bbb,
               0 4px 0 #b9b9b9,
               0 5px 0 #aaa,
               0 6px 1px rgba(0,0,0,.1),
               0 0 5px rgba(0,0,0,.1),
               0 1px 3px rgba(0,0,0,.3),
               0 3px 5px rgba(0,0,0,.2),
               0 5px 10px rgba(0,0,0,.25),
               0 10px 10px rgba(0,0,0,.2),
               0 20px 20px rgba(0,0,0,.15);
}

Webkit border radius fix

  -webkit-background-clip: padding-box;

XBrowser Border-radius (CSS3PIE)

.roundbox {
-moz-border-radius:8px;
-webkit-border-radius:8px;
-khtml-border-radius:8px;
border-radius:8px;
behavior: url(/PIE.htc);
}

Better IE compatibility

<!--[if IE]>
<script src="http://html5shim.googlecode.com/svn/trunk/html5.js"></script>
<![endif]-->

CSS3 Tooltips

a {
  color: #900;
  text-decoration: none;
}

a:hover {
  color: red;
  position: relative;
}

a[title]:hover:after {
  content: attr(title);
  padding: 4px 8px;
  color: #333;
  position: absolute;
  left: 0;
  top: 100%;
  white-space: nowrap;
  z-index: 20px;
  -moz-border-radius: 5px;
  -webkit-border-radius: 5px;
  border-radius: 5px;
  -moz-box-shadow: 0px 0px 4px #222;
  -webkit-box-shadow: 0px 0px 4px #222;
  box-shadow: 0px 0px 4px #222;
  background-image: -moz-linear-gradient(top, #eeeeee, #cccccc);
  background-image: -webkit-gradient(linear,left top,left bottom,color-stop(0, #eeeeee),color-stop(1, #cccccc));
}

CSS3 background-size

body {
  background: #000 url(http://birdoflight.files.wordpress.com/2009/10/frida-kahlo-1.jpg) center center fixed no-repeat;
  -moz-background-size: cover;
  background-size: cover;
}

@media only all and (max-width: 1024px) and (max-height: 768px) {
  body {   
    -moz-background-size: 1024px 768px;
    background-size: 1024px 768px;
  }
}

Cross Browser CSS Page Curl Shadow

.page-curl {
position: relative;
background: #ffffff;
background: -moz-linear-gradient(top, #ffffff 0%, #e5e5e5 100%);
background: -webkit-gradient(linear, left top, left bottom, color-stop(0%,#ffffff), color-stop(100%,#e5e5e5));
filter: progid:DXImageTransform.Microsoft.gradient( startColorstr='#ffffff', endColorstr='#e5e5e5',GradientType=0 );
-webkit-box-shadow: 0px 0px 3px rgba(0, 0, 0, 0.3);
-moz-box-shadow: 0px 0px 3px rgba(0, 0, 0, 0.3); }

.page-curl:after {
z-index: -1;
position: absolute;
background: transparent;
width: 70%;
height: 55%;
content: '';
right: 10px;
bottom: 10px;
-webkit-transform: skew(15deg) rotate(5deg);
-webkit-box-shadow: 8px 12px 10px rgba(0, 0, 0, 0.3);
-moz-transform: skew(15deg) rotate(5deg);
-moz-box-shadow: 8px 12px 10px rgba(0, 0, 0, 0.3); }

.page-curl:before {
z-index: -2;
position: absolute;
background: transparent;
width: 70%;
height: 55%;
content: '';
left: 10px;
bottom: 10px;
-webkit-transform: skew(-15deg) rotate(-5deg);
-webkit-box-shadow: -8px 12px 10px rgba(0, 0, 0, 0.3);
-moz-transform: skew(-15deg) rotate(-5deg);
-moz-box-shadow: -8px 12px 10px rgba(0, 0, 0, 0.3); }

CSS3 Blurry Text

.blur {
   color: transparent;
   text-shadow: 0 0 5px rgba(0,0,0,0.5);
}

Fix IE6/7 double margin/padding bug

ul li
{
  float: right;
  margin-right: 10px;
  *display: inline; /*Target IE7 and bellow*/
  _display: inline; /*Target IE6 and bellow*/
}
/* This example fixes the double right margin bug */

The order of link pseudo-classes

a:link {color: blue;}
a:visited {color: purple;}
a:hover {color: red;}
a:active {color: yellow;}

HTML Meta Tags for Responsive Layouts

<meta name="viewport" content="width=device-width,initial-scale=1,maximum-scale=1,user-scalable=no">
<meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1">
<meta name="HandheldFriendly" content="true">

 Reference ahrefmagazine.com/web-design/30-useful-css-snippets-for-developers

Code smells in CSS

“How can you tell if your CSS code smells? What are the signs that the code is sub-optional, or that the developer hasn’t done a good job? What do you look for in the code to determine how good or bad it is?”

I thought I would extend Chris’ great answer with my own, additional take on things…

My day-to-day life is spent working in-house at BSkyB… I work on big websites, the last of which took me over a year to build the front-end for (and it’s still ongoing). For me, in my world, bad CSS is a very specific and troublesome thing; when you’re working on one site for months on end, you can’t afford poor code, be it CSS or otherwise, and any bad code needs righting.

I’m going to share just a few things (there will, no doubt, be things that I have missed) that I look out for in CSS that will give you and idea as to its quality, its maintainability and its integrity…

Undoing styles

Any CSS that unsets styles (apart from in a reset) should start ringing alarm bells right away. The very nature of CSS is that things will, well, cascade and inherit from things defined previously. Rulesets should only ever inherit and add to previous ones, never undo.

Any CSS declarations like these:

border-bottom:none;
padding:0;
float:none;
margin-left:0;

…are typically bad news. If you are having to remove borders, you probably applied them too early. This is really hard to explain so I’ll go with a simple example:

h2{
    font-size:2em;
    margin-bottom:0.5em;
    padding-bottom:0.5em;
    border-bottom:1px solid #ccc;
}

Here we’re giving all h2s our usual font-size and margin for spacing, but also a bit of padding and a keyline on the bottom edge to visually separate it from the next element on the page. But, perhaps we have a circumstance in which we don’t want that keyline, perhaps we have a situation where we want a h2 to not have that border and padding. We’d likely end up with something like this:

h2{
    font-size:2em;
    margin-bottom:0.5em;
    padding-bottom:0.5em;
    border-bottom:1px solid #ccc;
}
.no-border{
    padding-bottom:0;
    border-bottom:none;
}

Here we have ten lines of CSS and one ugly class name. What would have been better is this:

h2{
    font-size:2em;
    margin-bottom:0.5em;
}
.headline{
    padding-bottom:0.5em;
    border-bottom:1px solid #ccc;
}

Here we have eight lines of CSS, no undoing anything, and a nice, sensible class name.

As you go down a stylesheet you should only ever be adding styles, not taking away. If you find you are having to undo styling as you go down your document the chances are you jumped the gun and started adding too much too soon.

This was a very timid example, but it helps illustrate my point perfectly. Imagine CSS like this over tens of thousands of lines… that’s a lot of bloat and a lot of unnecessary undoing. Peg things onto simpler things that came before it, do not start too complex and risk having to undo your work later on; you’ll end up writing more CSS to achieve less styling.

As soon as I see CSS that undoes previous styling, I can be pretty sure that it’s because something was poorly architected and that the order in which things were built/written needs a rework.

Magic numbers

These are a particular bugbear of mine. I loathe magic numbers.

A magic number is a value that is used ‘because it just works’. Take the following example:

.site-nav{
    [styles]
}
    .site-nav > li:hover .dropdown{
        position:absolute;
        top:37px;
        left:0;
    }

top:37px; here is a magic number; the only reason it works, presumably, is because the lis inside .site-nav happen to be 37px tall, and the .dropdown flyout menu needs to appear at the bottom of it.

The problem here is that 37px is entirely circumstantial and as such, we should place no faith in that number. What if someone changes the font-size in .site-nav and now everything is 29px tall? This number is no longer valid and the next dev needs to know to update it.

What happens when Chrome does render the lis at 37px, but IE renders it at 36px? That number only works in one situation.

Never, ever use numbers just because they work. In this situation we’d be far better off replacing top:37px; with top:100%;, which basically means ‘all the way from the top’.

Magic numbers have several problems associated with them. As above, they cannot be relied upon, but also, with their very ‘just because it works’ nature, it’s difficult to communicate to another dev where that number came from. If you had a more complex example which used a magic number—and that magic number became invalid—you are faced with one or more of the following problems:

  • The next dev doesn’t know where the magic number came from, so they delete it and are back at square one.
  • The next dev is a cautious dev who, because he doesn’t know where the magic number came from, decides to try and fix the problem without touching that magic number. This means that an old, outdated, hacky magic number stays in the code, and the next dev simply hacks away on top of it. You are now hacking on top of a hack.

Magic numbers are bad news; they soon become out of date, they confuse other developers, they cannot be explained, they cannot be trusted.

There’s nothing worse than hitting someone else’s code and seeing an inexplicable number. You’re left wondering what the hell it does, why it’s needed and whether or not you should dare touch it.

As soon as I see magic numbers in CSS I start asking questions. Why is this here? What does it do? Why does that number work? How can you achieve the same without that magic number?

Avoid magic numbers like the plague.

Qualified selectors

Qualified selectors are ones like:

ul.nav{}
a.button{}
div.header{}

Basically, selectors who are needlessly prepended by an element. These are bad news because:

  • They totally inhibit reusability on another element.
  • They increase specificity.
  • They increase browser workload (decreasing performance).

These are all bad traits. Those selectors can, and should be:

.nav{}
.button{}
.header{}

Now I know I can apply .nav to an ol, I can apply .button to aninput, and—when the site gets ported over to HTML5—I can quickly swap out my header div for a header element without worrying about invalidating any styles.

With regards performance, this is only a very slight issue, however it is an issue nonetheless. Why make a browser look for a class .button on an a when you could just ask it to look for.button and be done? By qualifying selectors you are increasing a browser’s workload.

More extreme examples might be:

ul.nav li.active a{}
div.header a.logo img{}
.content ul.features a.button

All of these selectors can be trimmed down massively, or totally rewritten, to:

.nav .active a{}
.logo > img {}
.features-button{}

Which will help us:

  • Save actual amounts of code
  • Increase performance
  • Allow greater portability
  • Reduce specificity

As soon as I spot overqualified selectors when I scroll down a stylesheet I instantly want to know why they’re written so verbosely and how we can trim them down to as short as possible.

Hard-coded/absolute values

Not unlike magic numbers, hard-coded values are also bad news. A hard-coded value might be something like this:

h1{
    font-size:24px;
    line-height:32px;
}

line-height:32px; here is not cool, it should be line-height:1.333

Line heights should always be set relatively in order to make them more forgiving and flexible. If you ever change the font-size of ah1, you want to know that your line-height will track it. Not having a relative line-height means that if you ever need to modify a h1 you will likely end up with something like this:

h1{
    font-size:24px;
    line-height:32px;
}

/**
 * Main site `h1`
 */
.site-title{
    font-size:36px;
    line-height:48px;
}

Here we need to keep on adding fixed line-heights indefinitely as our initial one was never flexible enough. With a unitless and/or relative line-height, we’d have simply needed:

h1{
    font-size:24px;
    line-height:1.333;
}

/**
 * Main site `h1`
 */
.site-title{
    font-size:36px;
}

This may not seem like a massive difference, but on every text element over a large project, this has a big impact.

N.B. this applies to a lot more than just line-heights; basicallyany hard-coded absolute in a stylesheet needs treating with caution and suspicion.

Hard-coded values are not very future proof, flexible or forgiving, and thus should be avoided. The only things that should everreally have hard-coded values are things like sprites which willalways need to be a certain size no matter what.

As soon as I see a hard-coded unit in a stylesheet I want to know why it was required and how it could be avoided.

Brute forcing

This one is in a similar vein to hard-coded numbers, but a little more specific. Brute forcing CSS is when you use hard-coded magic numbers and a variety of other techniques to force a layout to work. Take for example:

.foo{
    margin-left:-3px;
    position:relative;
    z-index:99999;
    height:59px;
    float:left;
}

This is terrible CSS. All of these declarations are heavy-handed, brute-forced, layout-affecting declarations which are clearly only used to force something to render as and where it’s wanted.

This type of CSS is indicative of either a poorly coded layout that requires this kind of manipulation, a lack of understanding of box-model and layout, or both.

Well coded layouts should never need brute-forcing, and a solidunderstanding of box model, layout and taking a look at your computed styles more often should mean that you’d rarely end up in a situation like this.

As soon as I see brute-forced CSS I want to know how it happened, and how far back we need to unpick things before we can lay things out more rationally.

Dangerous selectors

A ‘dangerous selector’ is one with far too broad a reach. A really obvious and simple example of a dangerous selector might be:

div{
   background-color:#ffc;
   padding:1em;
}

This will instantly scream at any developer; why on earth would you want to carpet bomb every div on your site? Good question, so why would anyone ever want to have a selector like aside{}for example? Or header{}, or ul{}? Selectors like these are way,way too far reaching and will ultimately lead to us having to undo CSS, as per the section previously.

Let’s look at the header{} example more closely…

A lot of people use a header element to mark up their site’s main header—which is fine—however, if you style that site-wide header like this:

header{
    padding:1em;
    background-color:#BADA55;
    color:#fff;
    margin-bottom:20px;
}

…then that’s not so fine. The header element does not mean ‘your site’s main header’ and, as per the spec, the header element can be used multiple times in multiple contexts. This should be targeted via a selector more like .site-header{}, for example.

To give such specific styling to such a generic selector is dangerous. Your styles will leak out into areas they shouldn’t as soon as you start trying to use that element again, and you’ll need to start undoing styles (adding more code to take styles away) in order to combat this.

Make sure your selectors have good selector intent.

Take the following:

ul{
    font-weight:bold;
}
header .media{
    float:left;
}

As soon as I see selectors that end in either a type selector or a very basic abstraction class, as above, I start to panic. I know that these selectors are far too broad and will quickly run us into trouble. As soon as we try and reuse those elements we will find that they’re inheriting styles we don’t necessarily want because, somewhere, there’s a really broad selector managing to reach them.

Reactive !important

!important is fine. It’s fine and it’s a, well, important tool. However, !important should only be used in certain circumstances.

!important should only ever be used proactively, not reactively.

By this I mean that there are times when you know you will always, always want a style to take precedence, and you will know this up front.

For example, you know that you will always want errors to be red, so this rule is totally fine:

.error-text{
    color:#c00!important;
}

If the error occurs in a div where the text is always blue, we can be confident that we want to break that rule in the case of errors. We always want errors to be red because it’s an error, and user messaging should always remain consistent. Here we can proactively add !important because we know we always want errors to be red.

Where !important is bad is when it is used reactively, that is to say, it’s been used to get someone out of a specificity problem, or they’re in a bit of a bind and resort to !important to force things to work. This is using !important reactively and this is bad news.

Using !important reactively is just a way of circumventing the problems caused by ill-formed CSS. It doesn’t fix any problems, it only fixes the symptoms. The problems still exist, but now with and added layer of super-specificity that will take yet more specificity to overcome.

I have no qualms whatsoever with !important, as long as it has been used proactively. As soon as I see reactive use of !importantI know right away that it’s likely because of some poorly architected CSS, and that the solution is a refactor, not a hasty addition of heavy-handed specificity.

IDs

This one is very specific to me, and to larger teams. I have written before about how IDs are a bad idea because of their heightened specificity; they are of no use to anyone and should never be used in CSS. Use IDs in HTML for fragment identifiers and JS hooks, but never in CSS.

The reasons are simple:

  • IDs can never be used more than once in a page.
  • Classes can exist only once, or a million times in a page.
  • IDs can often have their traits abstracted out into many reusable classes.
  • An ID is 255 times more specific than one class…
  • This means you’d need 256 chained classes to override one ID.

If that last bullet point hasn’t convinced you not to use them then I don’t know what will…

As soon as I see an ID in a stylesheet, I want it replaced with a class. Specificity is how projects start to spiral so it is vital to keep it low.

Fun exercise: try elegantly solving this problemClue: this isn’t elegantnor is this.

Loose class names

A ‘loose’ class name is one that isn’t specific enough for its intended purpose. Imagine a class of .card. What does this do?

This class name is very loose, and loose class names are very bad for two main reasons:

  • You can’t necessarily glean its purpose from the class alone.
  • It’s so vague that it could very easily be redefined accidentally by another dev.

The first point is the simplest; what does .card mean? What does it style? Is it a Trello-esque concept where a card is a component? Is it a class that you add to a playing card on a poker website? Does it refer to an image of a credit card? It’s difficult to know, because it’s far too loose. Let’s imagine it means credit card; this class would have been much better had it been .credit-card-image{}. A lot longer, yes; a lot better, hell yes!

The second problem with loose class names is that they can very easily be (accidentally) reassigned/redefined. Let’s say you’re working on an commerce site using .card again, and it refers to the user’s credit card linked to their account. Now imagine another dev comes along and wants to add some functionality whereby you can send a purchase to someone as a present, with the option to add a card with a message on it. Their temptation might be to use .card again somewhere, which is wrong, but in certain (albeit unlikely events) this could lead to your .card class being redefined and overwritten.

All this can be avoided by using much stricter class names. Classes like .card and .user and suchlike are far too loose, making them hard to quickly understand, and easy to accidentally reuse/override.

As soon as I see loose class names I start having to work out what it actually refers to, and asking what we can rename it to. Class names should be as specific as possible.

Final word

So there we have it, just a few of the many things I perceive to be code smells in CSS. These are things that I look out for on a daily basis and strive to avoid at all costs. When working on larger projects that last for months and months (and, ultimately, years) it is vital to keep a tight ship, and keeping an eye out for the above—among other things—is paramount. (I can’t stress enough how small a sub-set of things this is; there is a lot more that I look out for.)

Now, of course, there are exceptions to every rule, but they will need assessing on a case by case basis. For the most part, however, these are all things I work hard to avoid, and can spot a mile off in CSS