Hardware and software setup

The element is transparent. CSS transparency - cross-browser solution

/* 06.07.2006 */

CSS transparency (css opacity, javascript opacity)

The transparency effect is the topic of this article. If you are interested to know how to make html page elements transparent using CSS or Javascript and how to achieve cross-browser (same work in different browsers) considering Firefox browsers, Internet Explorer, Opera, Safari, Konqueror, then you are welcome. In addition, consider a ready-made solution for gradually changing transparency using javascript.

CSS opacity (CSS transparency)

CSS opacity symbiosis

By symbiosis, I mean combining different styles to different browsers in one CSS rule to get the desired effect, i.e. for cross-browser implementation.

Filter:progid:DXImageTransform.Microsoft.Alpha(opacity=50); /* IE 5.5+*/ -moz-opacity: 0.5; /* Mozilla 1.6 and below */ -khtml-opacity: 0.5; /* Konqueror 3.1, Safari 1.1 *//* CSS3 - Mozilla 1.7b+, Firefox 0.9+, Safari 1.2+, Opera 9 */

In fact, the first and last rules are necessary, for IE5.5+ and browsers that understand CSS3 opacity, and the two rules in the middle obviously don’t make any difference, but don’t really interfere either (decide for yourself whether you need them).

Javascript opacity symbiosis

Now let's try to set the transparency through the script, taking into account the features of different browsers described above.

Function setElementOpacity(sElemId, nOpacity) ( var opacityProp = getOpacityProperty(); var elem = document.getElementById(sElemId); if (!elem || !opacityProp) return; // If there is no element with the specified id or the browser does not support any of the methods known to the function for controlling transparency if (opacityProp=="filter") // Internet Exploder 5.5+ ( nOpacity *= 100; // If transparency is already set, then we change it through the filters collection, otherwise we add transparency through style.filter var oAlpha = elem.filters["DXImageTransform.Microsoft.alpha"] || elem.filters.alpha; if (oAlpha) oAlpha.opacity = nOpacity; else elem.style.filter += "progid:DXImageTransform.Microsoft.Alpha(opacity="+nOpacity+")"; // In order not to overwrite other filters, use "+=") else // Other browsers elem.style = nOpacity; ) function getOpacityProperty() ( if (typeof document.body.style.opacity == "string") // CSS3 compliant (Moz 1.7+, Safari 1.2+, Opera 9) return "opacity"; else if (typeof document.body.style.MozOpacity == "string") // Mozilla 1.6 and earlier, Firefox 0.8 return "MozOpacity"; else if (typeof document.body.style.KhtmlOpacity == "string") // Konqueror 3.1, Safari 1.1 return "KhtmlOpacity"; else if (document.body.filters && navigator.appVersion.match(/MSIE ([\d.]+);/)>=5.5) // Internet Exploder 5.5+ return "filter"; return false; //no transparency }

The function takes two arguments: sElemId - element id, nOpacity - real number from 0.0 to 1.0 setting CSS3 opacity transparency.

I think it's worth explaining the IE part of the setElementOpacity function code.

VaroAlpha = elem.filters["DXImageTransform.Microsoft.alpha"] || elem.filters.alpha; if (oAlpha) oAlpha.opacity = nOpacity; else elem.style.filter += "progid:DXImageTransform.Microsoft.Alpha(opacity="+nOpacity+")";

The question may arise, why not set transparency by assigning (=) to the property elem.style.filter = "..."; ? Why use "+=" to add the filter property to the end of the string? The answer is simple, in order not to "overwrite" other filters. But at the same time, if you add a filter this way a second time, it will not change the previously set values ​​of this filter, but will simply be added to the end of the property line, which is not correct. Therefore, if the filter is already set, then you need to manipulate it through the collection of filters applied to the element: elem.filters (but note that if the filter has not yet been assigned to the element, then it is impossible to manage it through this collection). Collection elements can be accessed either by filter name or by index. However, the filter can be specified in two styles, the short IE4 style, or the IE5.5+ style, which is taken into account in the code.

Smoothly change the transparency of an element

Ready solution. Using the opacity.js library

fadeOpacity(this.id, "oR1")"onmouseout=" fadeOpacity.back(this.id)"src="/img/strawberry.jpg" width="100" height="80" /> fadeOpacity(this.id, "oR1")"onmouseout=" fadeOpacity.back(this.id)"src="/img/tomato.jpg" width="82" height="100" /> fadeOpacity(this.id, "oR1")"onmouseout=" fadeOpacity.back(this.id)"src="/img/sweet_cherry.jpg" width="98" height="97" />

Basic steps:

  1. We connect the library of functions;
  2. Define the rules using the method fadeOpacity.addRule();
  3. We call the method fadeOpacity() to change the transparency from the start value to the end value, or fadeOpacity.back() to return to the initial value of the transparency level.

Chewing

How to connect the library, I think, can be seen from the example above. Now it is worth explaining the definition of the rules. Before calling methods smooth change transparency, you need to define the rules by which the process will be executed: you need to define the initial and final transparency, and, if desired, specify a delay parameter that affects the speed of the transparency change process.

Rules are defined using the method fadeOpacity.addRule

Syntax: fadeOpacity.addRule(sRuleName, nStartOpacity, nFinishOpacity, nDalay)

Arguments:

  • sRuleName - rule name, set arbitrarily;
  • nStartOpacity and nFinishOpacity - start and end transparency, numbers in the range from 0.0 to 1.0 ;
  • nDelay - delay in milliseconds (optional argument, default is 30).

We call the transparency fading itself using the fadeOpacity(sElemId, sRuleName) methods, where sElemId is the element id, and sRuleName is the rule name. To return transparency to the initial state the fadeOpacity.back(sElemId) method is used.

:hover for simple transparency change

I also note that for a simple change in transparency (but not a gradual change), the pseudo-selector is just right :hover, which allows you to define styles for an element when you hover over it with the mouse.

Note that the image is placed inside the A element. The fact is that Internet Explorer up to version 6 understands the :hover pseudo-selector, only applied to links, and not to any element, as it should be in CSS (in IE7, the situation has been corrected).

Transparency and jagged text in IE

With the release of Windows XP, anti-aliasing of screen fonts appeared using the method clear type, and with it the side effects in IE when using this anti-aliasing method. Regarding our case, if transparency is applied to an element with text with the ClearType anti-aliasing method enabled, then the text stops displaying normally (bold text - bold, for example, doubles, various artifacts may also appear, for example, in the form of dashes, jagged text). In order to fix the situation, for IE you need to set the background color, CSS property background color The element to which the transparency is applied. Luckily, IE7 has fixed the bug.

In this lesson, we'll take a look at these css properties - opacity And RGBA. Property Opacity is responsible only for the transparency of elements, and the function RGBA- for color and transparency, if you specify the transparency value of the alpha channel.

CSS Opacity

Numeric value for opacity set in the range from 0.0 to 1.0, where zero is full transparency, and one, on the contrary, is absolute opacity. For example, in order to see 50% transparency, you need to set the value to 0.5. It must be borne in mind that opacity propagates to all child elements of the parent. And this means that the text on a translucent background will also be translucent. And this is already a very significant drawback, the text does not stand out so well.




Transparency via CSS Opacity




The screenshot clearly shows that the black text has become as translucent as the blue background.

Div (
background: url(images/yourimage.jpg); /* Background image */
width: 750px
height: 100px;
margin: auto;
}
.blue(
background: #027av4; /* Translucent background color */
opacity: 0.3 /* Background translucency value */
height: 70px;
}
h1(
padding: 6px
font-family: Arial Black;
font-weight: bolder;
font-size: 50px;
}

CSS transparency in RGBA format

Format for writing color RGBA, is a more modern alternative for the property opacity. R (red), G (green), B (blue) means: red, green, blue. last letter A- means the alpha channel, which sets the transparency. RGBA Unlike Opacity does not affect child elements.

Now let's look at our example using RGBA. Let's replace these lines in styles.

Background: ##027av4; /* Background color */
opacity: 0.3 /* background translucency value */

to the next one line

Background: rgba(2, 127, 212, 0.3);

As you can see, the transparency value of 0.3 is the same for both methods.

The result of the RGBA example:

The second screenshot looks much better than the first one.

Playing with the translucency of the background of the blocks, you can achieve interesting effects on the site. It is important that these translucent blocks go on top of a colorful pattern, such as a photograph. Only in this case the effect will be noticeable. This technique has been used in design for a long time, even before the advent of any CSS3, it was implemented purely in graphic programs.

If the customer requires the layout to look good in older versions of the browser Internet Explorer then add property filter and do not forget to comment out so that the validity of the code does not suffer.



Output

Format RGBA support all modern browsers except Internet Explorer. It is also very important that RGBA flexible, it acts only on a specific given element, without affecting the children. It is clear that it is more convenient for the coder. My choice is definitely in favor of the format RGBA for getting transparency in css.

For better consolidation of the material and greater clarity, I suggest you go through.

To control the transparency of page elements, use the property CSS opacity. According to the specification, it is applicable to nodes of any type and is supported in all modern browsers. With it, you can create interesting design or implement a convenient interactive user experience.

Possible values

The syntax for the opacity property in css looks like this:

selector ( opacity: 1; ) selector ( opacity: 0; ) selector ( opacity: 0.4; )

Numeric values ​​in the range from 0 to 1 are accepted as input. The parameter can be fractions of one, while a dot is used as a separator between the integer and fractional parts in CSS.

An element with zero transparency becomes invisible, but still continues to take its place on the page and retains the ability to interact with the user.

If the property value is non-zero, then the actual transparency will be calculated as a percentage of some upper limit. In a normal situation, opacity: 1 specifies the full opacity of the element.

Transparency of child nodes

However, if the element has a parent whose transparency differs from one, the calculation changes. A descendant cannot be "less transparent" than any of its ancestors. The value of the opacity CSS property of the parent block becomes the upper limit of the transparency of the child node.

Parent ( opacity: 0.7; ) child ( opacity: 1; )

In this situation, the child element will be 30% transparent, even though the opacity value is one.

Examples of using

Example 1. Translucency. It is necessary that the main background of the block be visible under the target element.

Target ( background: black; opacity: 0.5; )

Not only the background becomes translucent target block but also text.

Example 2: Dynamic transparency control. The value of the CSS opacity property of the target block changes when you hover over it.

Target ( opacity: 0.2; ) .target:hover ( opacity: 1; )

Dynamic transparency

The last example demonstrates that transparent elements continue to respond to page events such as hover. This allows you to use javascript to control the CSS opacity property, as well as use the transition and animation mechanisms to smoothly change the display mode.

To access transparency from a script, you need to refer to the style object of a particular element.

// get current opacity value var opacity = element.style.opacity; // setting a new value element.style.opacity = 0.4;

The smooth disappearance of a block can be implemented using the transition CSS property:

Element ( opacity: 0.1; transition: opacity 1000ms; ) element:hover ( opacity: 0.8; transition: opacity 2000ms; )

Now the element node will change its opacity from 10% to 80% on mouseover within one second, and when the cursor leaves, it will dim to its original value within two seconds.

The CSS opacity property, combined with the transition mechanism, allows you to create beautiful effects.

Alpha channel instead of opacity

The main subtleties of the opacity mechanism in CSS:

  • its action extends not only to the background of the block, but also to its text content, which is preferable to be left clear;
  • child elements cannot be less transparent than parent elements.

If these effects complicate the life of the layout designer, instead of opacity, you should simply use transparent background, specifying its value in RGBA or HSLA format.

Transparency in CSS is quite a trendy technique lately, which causes difficulties in cross-browser implementation. Until now, there is no universal method that would allow to implement transparency for all browsers. However, the situation has improved markedly in recent years.

This article details existing approaches, and provides code examples and explanations to help you achieve the same result in all browsers with minimal effort.

Another point worth mentioning is that although transparency has been around for a few years now, it has never been part of the CSS standard. This is a non-standard property that should become part of the CSS3 specification.

old approach

In older versions of Firefox and Safari, you need to apply the property like this:

#myElement ( -khtml-opacity: .5; -moz-opacity: 0.5; )

The -khtml-opacity property was used in older versions of webkit browsers. This property is deprecated and is no longer needed unless you are certain that a significant portion of your site's traffic comes from visitors using Safari 1.x, which is of course unlikely.

The next line uses the -moz-opacity property, which worked for a very long time. early versions Mozilla engine. Firefox stopped supporting it in version 0.9.

CSS transparency in Firefox, Safari, Chrome and Opera

For most modern browsers it is enough to use the following property:

#myElement ( opacity: .7; )

In the above example, the element is set to 70% opacity (30% transparency). That is, if we set the value to one, then the element will be opaque, and, accordingly, setting this value to zero will make it invisible.

The opacity property handles 2 decimal digits. That is, the value ".01" will differ from the value ".02", although this is hardly noticeable.

CSS transparency for Internet Explorer

As usual, Internet Explorer is not friendly with other browsers. In addition, we now have three versions of this browser in fairly wide use, the transparency setting in each of which is different and sometimes requires additional effort to obtain a positive result.

#myElement ( filter: alpha(opacity=40); )

This example uses the filter property, which works in versions 6-8, but there is one limitation for versions 6 and 7: the element's hasLayout property must be set to true . This property is present only in IE and you can read more about it, for example, on Habré.

Another way to set transparency using CSS in IE8 is to use the following approach (note the comments):

#myElement ( filter: progid:DXImageTransform.Microsoft.Alpha(opacity=40); /* works in IE6, IE7 and IE8 */ -ms-filter: "progid:DXImageTransform.Microsoft.Alpha(opacity=40)"; / * IE8 only */ )

The first line will work in all currently used versions, the second - only in IE8. Note that the second line uses the -ms- prefix and the value is enclosed in quotation marks.

Setting and changing CSS transparency with JavaScript or jQuery

You can use the following code to set transparency:

Document.getElementById("myElement").style.opacity = ".4"; // for most browsers document.getElementById("myElement").style.filter = "alpha(opacity=40)"; // for IE

Of course, in this case it is much easier to use jQuery, and it will also work in all browsers:

$("#myElement").css(( opacity: .4 )); // works in all browsers

You can animate this property:

$("#myElement").animate(( opacity: .4 ), 1000, function() ( // Animation complete; this code works in all browsers. ));

RGBA function

CSS3 plans to support the alpha channel with the rgba function. This feature works in Firefox 3+, Opera 10.1+, Chrome 2+, Safari 3.1+. It is used like this:

#rgba ( background: rgba(98, 135, 167, .4); )

In this case, the last parameter indicates the level of opacity.

HSLA function

Like the previous function, CSS3 also allows you to set a translucent color using the HSLA function, whose parameters mean Hue (Hue), Saturation (Saturation), Brightness (Lightness) and Alpha channel (Alpha).

#hsla ( background: hsla(207, 38%, 47%, .4); )

An important point when using the rgba and hsla functions is that the transparency setting does not apply to child elements, while the use of the opacity property is inherited.

CSS transparency - cross-browser solution - 3.8 out of 5 based on 6 votes

In this tutorial, we will look at CSS transparency, learn how to give transparency to various elements of the page and achieve full cross-browser, i.e., the same work of this effect in different browsers.

How to set the transparency of any element

In CSS3, the opacity property is responsible for creating transparent elements, which can be applied to any element. This property has values ​​from 0 to 1, which determine the degree of transparency. Where 0 is fully transparent (the default value for all elements) and 1 is fully opaque. Values ​​are written as fractions: 0.1, 0.2, 0.3, etc.

Usage example:

Transparency

Cross browser transparency

Not all browsers perceive and implement the above opacity property in the same way. In some cases it is necessary to use a different property name or filters.

The CSS3 opacity property supports the following types Mozilla browsers 1.7+, Firefox 0.9+, Safari 1.2+, Opera 9+.

So good :) Browser like Internet Explorer up to version 9.0 doesn't support opacity property and to create transparency for this browser you need to use filter property and value alpha(Opacity=X) where X is an integer between 0 and 100 which determines the level of transparency. 0 is full transparency and 100 is full opacity.

Concerning Firefox browser prior to version 3.5 it supports the -moz-opacity property instead of opacity.

Browsers such as Safari 1.1 and Konqueror 3.1, built on the KHTML engine, use the -khtml-opacity property to control transparency.

How to set transparency in CSS so that it looks the same in all browsers? To create a cross-browser solution for the transparency of elements, they need to register not only one opacity property, but the following set of properties:

filter: alpha(Opacity=50); /* Transparency for IE */ -moz-opacity: 0.5; /* Support for Mozilla 3.5 and below */ -khtml-opacity: 0.5; /* Support for Konqueror 3.1 and Safari 1.1 */ opacity: 0.5; /* Support for all other browsers */

Transparency of various elements

Consider some examples of setting transparency certain elements, which are most often used on the page.

CSS image transparency.

Consider several options for creating a translucent image. In the following example, the first picture has no transparency, the second has 50% transparency, and the third has 30%.

Transparency

Result:

Transparency in CSS when hovering over an image.

It is often necessary to make a picture or any other element transparent at the moment when the cursor is hovered over it. This can be done at CSS help pseudo-class:hover. To do this, our picture needs to register two classes, one ordinary - this will be the inactive state of the picture and the second class with the pseudo-class: hover, here you need to specify the transparency of the picture at the time of hovering the cursor.

Transparency

You can see the result in the demo.

CSS background transparency

Here you need to remember that transparency applies to all nested elements and they cannot have more transparency than the nested element.

As an example, let's give a variant with a page background created using an image and a block with a background created using color and having a transparency of 50%.

Code example:

Transparency

Text

Here is the result of the above code:

Liked the article? Share with friends!
Was this article helpful?
Yes
Not
Thanks for your feedback!
Something went wrong and your vote was not counted.
Thanks. Your message has been sent
Did you find an error in the text?
Select it, click Ctrl+Enter and we'll fix it!