How to set transparency in css - transparent block. CSS transparency - cross-browser solution Smoothly changing element transparency

💖 Do you like it? Share the link with your friends
Creating a transparent background in HTML and CSS (opacity and RGBA effects)

The translucent effect of an element is clearly visible in the background image and has become widespread in various operating systems because it looks stylish and beautiful. The main thing is to have not a monochromatic pattern under the translucent blocks, but an image; it is in this case that transparency becomes noticeable.

This effect is achieved in a variety of ways, including old-fashioned methods like using a PNG image as a background, creating a checkered image, and the opacity property. But as soon as the need arises to make a floor in the block transparent background, these methods have unpleasant downsides.

Let's look at the translucency of text and background - how to use it correctly in website design:

The main feature of this property is that the transparency value affects all child elements within it, not just the background. This means that both the background and text will become translucent. You can increase the level of transparency by changing the opacity command from 0.1 to 1.

HTML 5 CSS 3 IE 9 opacity body ( background: url(images/cat.jpg); ) div ( opacity: 0.6; background: #fc0; /* Background color */ padding: 5px; /* Margins around text */ ) Creation and promotion of websites on the Internet

In web design, partial transparency is also used and is achieved through the RGBA color format, which is set only for the background of the element.

Typically in a design, only the background of an element should be translucent, and the text should be opaque to maintain readability. The opacity property is not suitable here because the text inside the element will also be partially transparent. It's best to use the RGBA format, which has an alpha channel, or in other words, a transparency value as part of it. The value is written rgba, then the values ​​of the red, blue and green color components are listed in parentheses, separated by commas. Last is transparency, which is set from 0 to 1, with 0 meaning full transparency, and 1 color opacity - the syntax for using rgba.

Semi-transparent background HTML 5 CSS 3 IE 9 rgba body ( background: url(images/cat.jpg); ) div ( background: rgba(0, 170, 238, 0.4); /* Background color */ color: #fff; / * Text color */ padding: 5px; /* Margins around the text */ ) Creation and promotion of websites on the Internet. The background opacity is set to 90% - semi-transparent background and opaque text.

To control the transparency of page elements, use the CSS opacity property. According to the specification, it applies to any type of node and is supported in all modern browsers. With its help, you can create an interesting design or implement convenient interactive user interaction.

Possible values

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

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

The input accepts numeric values ​​in the range from 0 to 1. The parameter can represent fractions of one, while a dot is used as a separator for the integer and fractional parts in CSS.

An element with zero transparency becomes invisible, but still continues to occupy 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 determines the complete opacity of the element.

Transparency child nodes

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

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 of the target block becomes translucent, but also the 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 transition and animation mechanisms to smoothly change the display mode.

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

// getting the current transparency value var opacity = element.style.opacity; // setting a new value element.style.opacity = 0.4;

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

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

Now the element node, when hovered with the mouse, will change transparency from 10 to 80% within one second, and when the cursor leaves, it will dim to its original value within two seconds.

The CSS opacity property in combination 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 effect extends not only to the background of the block, but also to its text content, which is preferably left clear;
  • child elements cannot be less transparent than their parent elements.

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

/* 06.07.2006 */

CSS transparency (css opacity, javascript opacity)

The transparency effect is the topic of this article. If you are interested in learning how to make HTML page elements transparent using CSS or Javascript, and how to achieve cross-browser compatibility (working the same in different browsers) taking into account Firefox browsers, Internet Explorer, Opera, Safari, Konqueror, then you are welcome. In addition, consider ready-made solution gradual change in transparency from using javascript.

CSS opacity (CSS transparency) CSS opacity symbiosis

By symbiosis I mean unification different styles For different browsers in one CSS rule to obtain the desired effect, i.e. to implement cross-browser compatibility.

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 needed, for IE5.5+ and browsers that understand CSS3 opacity, and the two rules in the middle obviously don’t make a difference, but they don’t really interfere either (decide for yourself whether you need them).

Javascript opacity symbiosis

Now let's try to set transparency through a 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 either one of the known functions of ways to control transparency if (opacityProp=="filter") // Internet Exploder 5.5+ ( nOpacity *= 100; // If transparency is already set, then change it through the filters collection, otherwise 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 transparency in CSS3 style opacity.

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

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+"");

One might wonder why not set transparency by assigning (=) to the property elem.style.filter = "..."; ? Why is "+=" used to append 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 in 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 a filter is already installed, then you need to manipulate it through the collection of filters applied to the element: elem.filters (but keep in mind 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 IE4 short style, or the IE5.5+ style, which is taken into account in the code.

Smoothly change the transparency of an element

Ready solution. We use the opacity.js library

img ( filter:alpha(opacity=30); -moz-opacity: 0.3; -khtml-opacity: 0.3; opacity: 0.3; ) // Create a rule for changing transparency: set the rule name, start and end transparency, as well as an optional parameter delays affecting the speed of transparency change fadeOpacity.addRule("oR1", .3, 1, 30); 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:
  • We connect the library of functions;
  • We define the rules using the fadeOpacity.addRule() method;
  • We call the fadeOpacity() method to change the transparency from the initial value to the final value, or fadeOpacity.back() to return to the initial value of the transparency level.
  • Let's chew

    How to connect the library, I think, can be seen from the example above. Now it’s worth explaining the definition of the rules. Before calling the methods for smoothly changing transparency, you need to define the rules by which the process will be performed: you need to determine the initial and final transparency, and also, if desired, specify a delay parameter that affects the speed of the process of changing transparency.

    Rules are defined using the fadeOpacity.addRule method

    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 through the methods fadeOpacity(sElemId, sRuleName), where sElemId is the id of the element, and sRuleName is the name of the rule. To return transparency to the initial state The fadeOpacity.back(sElemId) method is used.

    :hover to easily change transparency

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

    a:hover img ( filter:progid:DXImageTransform.Microsoft.Alpha(opacity=30); -moz-opacity: 0.3; -khtml-opacity: 0.3; opacity: 0.3; )

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

    Transparency and jagged text in IE

    With the release of Windows XP, screen font smoothing using the ClearType method appeared, 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 when the ClearType anti-aliasing method is enabled, then the text ceases to be displayed normally (bold text, for example, doubles, various artifacts may also appear, for example, in the form of dashes, jagged text). In order to correct the situation, for IE you need to set background color, CSS property background-color , the element to which transparency is applied. Fortunately, the bug has been fixed in IE7.

    orem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry"s standard dummy text ever since the 1500s, when an unknown printer took a galley of type and scrambled it to make a type specimen book. It has survived not only five centuries, but also the leap into electronic typesetting It was popularized in the 1960s with the release of Letraset sheets containing Lorem Ipsum passages, and more recently with desktop publishing software like Aldus PageMaker including versions of Lorem Ipsum.
    It is a long established fact that a reader will be distracted by the readable content of a page when looking at its layout. The point of using Lorem Ipsum is that it has a more-or-less normal distribution of letters, as opposed to using "Content here, content here", making it look like readable English. Many desktop publishing packages and web page editors now use Lorem Ipsum as their default model text, and a search for "lorem ipsum" will uncover many web sites still in their infancy. Various versions have evolved over the years, sometimes by accident, sometimes on purpose (injected humor and the like).

    So, today we will talk about transparency in html pages. You've probably come across transparent pop-up blocks, be it a photo gallery or login forms on some popular website. There are many uses for transparency in HTML. So how is it made and where can it be used?

    Well, first of all, let’s understand that our document has not only one monitor plane - it is generally 3-dimensional, I mentioned this in the article “Z-index”. Accordingly, even a completely transparent layer, if it were at the top of the display stack, would block access to other elements. This is one of the main uses of transparent blocks. Although a shading effect is usually used, a completely transparent layer will work exactly the same. So, for example, a lot of popular photo galleries work; a shaded layer is organized in which photos and controls for them are displayed. The rest of the page is “covered” with a (semi) transparent layer, blocking access to all other elements on the page. Those. You will not be able to leave the page by clicking any link on it - all the text is covered with a background. To return to the body of the site, they usually provide controls for closing the gallery, login form, etc. Control showing/hiding transparent blocks using javascript. Unfortunately, there is no alternative to it. Without using it, the user will either not see the transparent block at all, or will not be able to close it without leaving the current page. I note that visibility or display properties are used for this.

    So how is transparency actually organized in html? Setting element transparency is generally not included in the CSS specification, so you have to use several instructions at once to create it. Some browsers (ie) will work with one option, others with another. Ie uses the built-in filter functionality, other browsers use the "opacity" property, which is set in the range from 0 (completely transparent object) to 1 (completely opaque). For example, in the case of 30% transparency, you should write "opacity:0.30; filter:alpha(opacity=30); ". The properties, as can be seen from the example, are similar - only in the first case a number from 0 to 1 is used, in the second a percentage notation is used. An example of such a block:



    tell friends