Eschon
Eschon

Reputation: 538

HTML opacity attribute vs CSS opacity

I know of two different ways of setting opacity in HTML:

<div opacity="0.5"></div> and

<div style="opacity: 0.5;"></div>

I also know how to set both of those in JavaScript:

div.setAttribute("opacity", 0.5); and

div.style.opacity = 0.5

Are there any major differences between those two methods? Should I prefer one over the other? (I guess I should at least be consistent)

Upvotes: 4

Views: 791

Answers (2)

misterManSam
misterManSam

Reputation: 24692

The only opacity attribute I am aware of is for use with SVGs:

Example Elements

The following elements can use the opacity attribute

Graphics elements [and] <a> <defs> <glyph> <g> <marker> <missing-glyph> <pattern> <svg> <switch> <symbol>

Your <div opacity="0.5"></div> doesn't work in HTML and therefore, to style HTML elements, opacity should be controlled with CSS.

Upvotes: 5

Mike Phils
Mike Phils

Reputation: 3505

CSS is always faster than Javascript. If your are able to do anything with CSS then why waste time with Javascript.

CSS precedence rules say inline and html attribute are given higher order then External or Embedded CSS. However inline CSS is not good practice, until it is required in your project for certain reason

Proper CSS opacity code:

img {
    opacity: 0.4;
    filter: alpha(opacity=40); /* For IE8 and earlier */
}

https://css-tricks.com/almanac/properties/o/opacity/

img {
  /* Theoretically for IE 8 & 9 (more valid) */
  /* ...but not required as filter works too */
  /* should come BEFORE filter */
  -ms-filter:"progid:DXImageTransform.Microsoft.Alpha(Opacity=50)"; // IE8

  /* This works in IE 8 & 9 too */
  /* ... but also 5, 6, 7 */
  filter: alpha(opacity=50); // IE 5-7

  /* Modern Browsers */
  opacity: 0.5;
}

Upvotes: -1

Related Questions