HTML Opacity Attribute and CSS Opacity
I know of two different ways to set opacity in HTML:
<div opacity="0.5"></div>
and
<div style="opacity: 0.5;"></div>
I also know how to set both of these in JavaScript:
div.setAttribute("opacity", 0.5);
and
div.style.opacity = 0.5
Are there any significant differences between the two methods? Should I give preference to one over the other? (I guess I should at least be consistent)
source to share
The only attribute opacity
I know of for use with SVG is :
Examples of elements
The following elements can use the opacity attribute
Graphic Elements [and]
<a>
<defs>
<glyph>
<g>
<marker>
<missing-glyph>
<pattern>
<svg>
<switch>
<symbol>
Yours <div opacity="0.5"></div>
doesn't work in HTML and so for styling HTML elements, opacity must be controlled with CSS.
source to share
CSS is always faster than Javascript. If you can do something with CSS, then why waste your time on Javascript.
CSS precedence rules say that the inline and html attribute is assigned in a higher order than external or inline CSS. However, inline CSS is not a good practice until it is required in your project for a specific reason.
Correct 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;
}
source to share