Home >Web Front-end >CSS Tutorial >How to make a background image transparent using CSS

How to make a background image transparent using CSS

不言
不言Original
2018-11-28 11:10:344451browse

The attribute needed to make the background image transparent in CSS is the opacity attribute, but when there is text, we need to separate the elements in order to prevent the text from being transparent.

How to make a background image transparent using CSS

The property in CSS that makes the background image transparent is the opacity property, but if you use it to create content with text, you will find that the text The content will also be transparent.

Now, let’s write a CSS that only makes the background image transparent.

First, let's take a look at the HTML code

<div class="content">
    <div class="bg"></div>
    <p>蒲公英</p>
</div>

.bg is an empty div, and "Dandelion" is written outside it.

In other words, the position attribute will be used to place the "dandelion" on top of the image. Let's look at the specific code example

First, give the relative position (position: relative;) to .content.

In order to make it easier to understand the background transparency, we first give a black background

.content{
    width: 450px;
    height: 300px;
    background: #000;
    position: relative; /*相对位置*/
}
p{
    color: #fff;
    font-weight: bold;
    text-align: center;
}

The effect is as follows:

How to make a background image transparent using CSS

# #Next, let’s set the .bg

Set the width and height to 100% and set the position to absolute position on the top left (left:0; top: 0;).

.bg{
    width: 100%;
    height: 100%;
    position: absolute;
    top: 0;
    left: 0;
    background: url(img/pugongying.jpg);
    background-size: cover;
    opacity: 0.5;
}

The effect is as follows:


How to make a background image transparent using CSS

In fact, the characters are underneath the transparent image.

So, compared to the background image fixed in absolute position, the content of p must be in front.

Therefore, p can also give it a stacking order by giving position: absolute;. (Because it is described as position: absolute;, you can also use z-index to manipulate the stacking order.)

Finally we move the text to the middle position


p{
    width: 100%;
    height: 1.5em;
    color: #fff;
    font-weight: bold;
    text-align: center;
    position: absolute;
    margin: auto;
    top: 0;
    bottom: 0;
}

The effect is as follows:

How to make a background image transparent using CSS


The above is the detailed content of How to make a background image transparent using CSS. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn