Cross-browser CSS to set DIV transparency

This Bootstrap LESS / CSS chunk will set transparency for the background of a div, but without modifying the transparency of its contents. This works on IE6+ and modern browsers (Safari, Firefox, Chrome) without using a PNG hack.

Bootstrap LESS version:

#content {
  @trans: rgba(255, 255, 255, 0.5);
  background: #fff;
  background: transparent\9;
  background: @trans;
  #gradient > .horizontal(@trans; @trans);
  zoom: 1;
}

CSS version:

#content {
  background: #fff;
  background: transparent\9;
  background: rgba(255, 255, 255, 0.5);
  background-image: -webkit-linear-gradient(left, color-stop(rgba(255, 255, 255, 0.5) 0%), color-stop(rgba(255, 255, 255, 0.5) 100%));
  background-image: linear-gradient(to right, rgba(255, 255, 255, 0.5) 0%, rgba(255, 255, 255, 0.5) 100%);
  background-repeat: repeat-x;
  filter: progid:DXImageTransform.Microsoft.gradient(startColorstr='#80ffffff', endColorstr='#80ffffff', GradientType=1);
  zoom: 1;
}

Annotated LESS version:

  /* Variable containing the amount of transparency (0.9) */
  @trans: rgba(255, 255, 255, 0.9);

  /* Set a white background for IE8 */
  background: #fff;

  /* IE 8 and below will ignore this due to the \9 hack : http://net.tutsplus.com/tutorials/html-css-techniques/quick-tip-how-to-target-ie6-ie7-and-ie8-uniquely-with-4-characters/ */
  background: transparent\9;

  /* Set the background color to the RGBA amount, for browsers that support this */
  background: @trans;

  /* Bootstrap mixin to generate a DXImageTransform and linear-gradient */
  #gradient > .horizontal(@trans; @trans);

  /* IE hack to invoke hasLayout: http://www.satzansatz.de/cssd/onhavinglayout.html */
  zoom: 1;

Demo:

Hello World! I’m 50% transparent but my content is not.

Comments

    Leave a comment