Css opacity and text

5 примеров, которые помогут понять, как работает CSS opacity

С помощью свойства CSS opacity можно контролировать CSS прозрачность HTML-элементов веб-страницы, таких как текст, изображения или фон. В данной статье мы расскажем об этом свойстве, а также приведем несколько примеров.

Как работает непрозрачность в CSS

Термин « непрозрачный » используется для описания объектов, которые полностью видимые. На веб-странице непрозрачный элемент имеет значение свойства opacity 1 , а полностью прозрачный — opacity , равное 0 . По умолчанию все элементы имеют opacity , равное 1 .

Значение от 0 до 1 определяет уровень прозрачности элемента. Например, следующий код уменьшит прозрачность CSS наполовину:

Элемент с непрозрачностью 0 будет полностью невидимым, но он все равно будет занимать физическое пространство на странице. Следовательно, чтобы сделать элемент видимым, нужно использовать в CSS свойство opacity , а также свойство visibility .

opacity было введено в CSS3 и на сегодняшний день хорошо поддерживается браузерами. Если ваш проект требует поддержки Internet Explorer 8 или более ранних версий, то нужно использовать свойство MS alpha filter следующим образом:

Читайте также:  Для css серверы мониторинг

Обратите внимание, что прозрачность фона CSS может задаваться десятичными значениями от 0 до 1 , а значения непрозрачности альфа-фильтра — в диапазоне от 0% до 100%.

Управление непрозрачностью родительских и дочерних элементов

Непрозрачность применяется ко всему элементу равномерно. Непрозрачность дочерних элементов также зависит от значения свойства его родителей. Для достижения различных уровней прозрачности нужно применять разные значения непрозрачности для родительских и дочерних элементов. Например:

Следующие примеры иллюстрируют, как дочерние элементы влияют на непрозрачность их родителей:

Управление непрозрачностью родительских и дочерних элементов

В первом примере для обоих полей задана непрозрачность 1 . Во втором примере родительское поле ( черное ) имеет непрозрачность 0.8 , а дочернее ( оранжевое ) — 1 . В третьем родительский элемент имеет непрозрачность 0.8 , а дочерний – 0.5 . Обратите внимание на разницу в цветовом тоне ( прозрачности ) оранжевого поля во всех трех примерах.

Использование свойства CSS opacity для создания прозрачных изображений

С помощью свойства opacity можно легко добавить прозрачность background CSS к изображениям. Предположим, что мы выводим одно и то же изображение на странице два раза. Следующий код сделает второе изображение прозрачным:

В результате мы получим следующее:

Использование свойства CSS opacity для создания прозрачных изображений

Изменение непрозрачности при наведении курсора мыши

Также можно управлять CSS прозрачностью изображений или других HTML-элементов при наведении курсора мыши. Для этого в предыдущем примере нужно изменить значение свойства opacity . Следующий код сделает изображение прозрачным при наведении на него курсора мыши:

#img1 < opacity: 1 >#img1:hover < opacity: 0.6 >

Использование свойства CSS opacity для фона

Задать непрозрачность фона можно двумя способами. В первом указывается значение opacity , как мы делали в предыдущих примерах:

Во втором способе необходимо указать значение альфа-канала в RGBA ( красный, зеленый, синий, альфа ) в объявлении цвета фона. Это делается следующим образом:

Изменяя значения R , G и B , можно получить прозрачность background CSS любого цвета. Аналогично можно получить непрозрачные дочерние элементы внутри прозрачных родительских элементов. Как правило, значение непрозрачности родительского элемента выше, чем у дочерних. Тем не менее, с помощью прозрачного фона можно сделать дочерние видимыми, сохраняя при этом прозрачность их контейнера.

Прозрачные рамки с помощью CSS

Если вы используете большие рамки и вам необходимо применить к ним непрозрачность, то нужно установить для цвета рамки значение альфа-канала, как показано в следующем примере:

На этом мы завершаем рассмотрение свойства CSS opacity . Мы привели примеры для различных случаев использования данного свойства, и надеемся, что они помогут вам лучше понять, как оно работает.

Источник

opacity

The opacity CSS property sets the opacity of an element. Opacity is the degree to which content behind an element is hidden, and is the opposite of transparency.

Try it

Syntax

opacity: 0.9; opacity: 90%; /* Global values */ opacity: inherit; opacity: initial; opacity: revert; opacity: revert-layer; opacity: unset; 

Values

Value Meaning
0 The element is fully transparent (that is, invisible).
Any strictly between 0 and 1 The element is translucent (that is, content behind the element can be seen).
1 (default value) The element is fully opaque (visually solid).

Description

opacity applies to the element as a whole, including its contents, even though the value is not inherited by child elements. Thus, the element and its children all have the same opacity relative to the element’s background, even if they have different opacities relative to one another.

Using opacity with a value other than 1 places the element in a new stacking context.

To change the opacity of a background only, use the background property with a color value that allows for an alpha channel. For example:

Accessibility concerns

If text opacity is adjusted, it is important to ensure that the contrast ratio between the color of the text and the background the text is placed over is high enough that people experiencing low vision conditions will be able to read the content of the page.

Color contrast ratio is determined by comparing the luminosity of the opacity-adjusted text and background color values. In order to meet current Web Content Accessibility Guidelines (WCAG), a ratio of 4.5:1 is required for text content and 3:1 for larger text such as headings. Large text is defined as 18.66px and bold or larger, or 24px or larger.

Formal definition

Initial value 1
Applies to all elements
Inherited no
Percentages map to the range [0,1]
Computed value The same as the specified value after clipping the to the range [0.0, 1.0].
Animation type by computed value type

Formal syntax

Examples

Setting opacity

The following example demonstrates how the opacity property changes the opacity of the entire element and content, thus making the text very hard to read.

HTML

div class="light">You can barely see this.div> div class="medium">This is easier to see.div> div class="heavy">This is very easy to see.div> 

CSS

div  background-color: yellow; font-weight: bold; font-size: 130%; > .light  opacity: 0.2; /* Barely see the text over the background */ > .medium  opacity: 0.5; /* See the text more clearly over the background */ > .heavy  opacity: 0.9; /* See the text very clearly over the background */ > 

Result

Setting opacity on hover

In the following example opacity is changed on hover, so the striped background image on the parent element shows through the image.

HTML

div class="wrapper"> img src="//interactive-examples.mdn.mozilla.net/media/dino.svg" alt="MDN Dino" width="128" height="146" class="opacity" /> div> 

CSS

img.opacity  opacity: 1; > img.opacity:hover  opacity: 0.5; > .wrapper  width: 200px; height: 160px; background-color: #f03cc3; background-image: linear-gradient( 90deg, transparent 50%, rgba(255, 255, 255, 0.5) 50% ); background-size: 20px 20px; > 

Result

Specifications

Browser compatibility

BCD tables only load in the browser

Found a content problem with this page?

This page was last modified on Jul 18, 2023 by MDN contributors.

Your blueprint for a better internet.

MDN

Support

Our communities

Developers

Visit Mozilla Corporation’s not-for-profit parent, the Mozilla Foundation.
Portions of this content are ©1998– 2023 by individual mozilla.org contributors. Content available under a Creative Commons license.

Источник

Change Text Opacity in CSS

Change Text Opacity in CSS

  1. Use the CSS opacity Property to Change Text Transparency in CSS
  2. Use the rgba() Function to Change Text Transparency in CSS

This article will introduce two methods to change the text opacity in CSS.

Use the CSS opacity Property to Change Text Transparency in CSS

The opacity property indicates the transparency of an element. It is generally indicated on a scale of 0 to 1 , where 0 is completely transparent.

That means it is completely invisible. Likewise, 1 is completely opaque, and 0.5 can be considered the benchmark of element opacity as it is 50% see-through.

For example, create a p element, and create a class before it. Type the text of your choice inside the p element.

Next, create a similar p element with the class after . Select the class before in CSS and specify red as the text color.

For the after class, set the color to red and opacity property to 0.4 , on a scale from 0 to 1 as your wish.

Similarly, we can also indicate the opacity of the element via percentage. 0% is completely transparent, and 100% is completely opaque. We can also use 40% in place of 0.4 .

 p class="before">  Liverpool  p>   p class="after">  Liverpool  p> 
.before   color:red; > .after   color:red;  opacity: 0.4; > 

Use the rgba() Function to Change Text Transparency in CSS

The rgba() function, in general, is used to insert the color to the element. The letters in rgba() stand for red, green, blue, and alpha.

It indicates that the function takes four values. The alpha option is an extension that denotes the opacity of the element.

We can indicate the intensity of the red, blue, or green color as an integer between 0 to 255 or 0% to 100%. For opacity , we can specify the 0-1 value and, of course, the 0%-100% range.

We can use the rgba() function as the option in the color property.

We will use the same HTML template as in the first example above for a demonstration. Select the class before and write the rgba() function in the color property in CSS.

Write the value 0, 0, 255 in the function, which is the color code for blue color. Use the same color code for the after class but add 0.5 for the opacity value.

As a result, the first text appears in blue, while the second one will be less opaque as we set the opacity in it.

 p class="before">  Liverpool  p>   p class="after">  Liverpool  p> 
.before   color: rgba(0, 0, 255); >  .after   color: rgba(0, 0, 255, 0.5); > 

Thus, considering all the facts, we used the opacity property and the rgba() function to change the text transparency.

Sushant is a software engineering student and a tech enthusiast. He finds joy in writing blogs on programming and imparting his knowledge to the community.

Related Article — CSS Opacity

Источник

Оцените статью