Html background image from link

HTML Background Images

A background image can be specified for almost any HTML element.

Background Image on a HTML element

To add a background image on an HTML element, use the HTML style attribute and the CSS background-image property:

Example

Add a background image on a HTML element:

You can also specify the background image in the element, in the section:

Example

Specify the background image in the element:

Background Image on a Page

If you want the entire page to have a background image, you must specify the background image on the element:

Example

Add a background image for the entire page:

Background Repeat

If the background image is smaller than the element, the image will repeat itself, horizontally and vertically, until it reaches the end of the element:

Example

To avoid the background image from repeating itself, set the background-repeat property to no-repeat .

Example

Background Cover

If you want the background image to cover the entire element, you can set the background-size property to cover.

Also, to make sure the entire element is always covered, set the background-attachment property to fixed:

This way, the background image will cover the entire element, with no stretching (the image will keep its original proportions):

Example

Background Stretch

If you want the background image to stretch to fit the entire element, you can set the background-size property to 100% 100% :

Try resizing the browser window, and you will see that the image will stretch, but always cover the entire element.

Example

Learn More CSS

From the examples above you have learned that background images can be styled by using the CSS background properties.

To learn more about CSS background properties, study our CSS Background Tutorial.

Источник

CSS Background Image – How to Add an Image URL to Your Div

Amy Haddad

Amy Haddad

CSS Background Image – How to Add an Image URL to Your Div

Say you want to put an image or two on a webpage. One way is to use the background-image CSS property.

This property applies one or more background images to an element, like a , as the documentation explains. Use it for aesthetic reasons, such as adding a textured background to your webpage.

Add an Image

It’s easy to add an image using the background-image property. Just provide the path to the image in the url() value.

The image path can be a URL, as shown in the example below:

Or it can be a local path. Here’s an example:

Add Multiple Images

You can apply multiple images to the background-image property.

That’s a lot of code. Let’s break it down.

Separate each image url() value with a comma.

background-image: url("https://amymhaddad.s3.amazonaws.com/morocco-blue.png"), url("https://amymhaddad.s3.amazonaws.com/oriental-tiles.png"); 

Now position and enhance your images by applying additional properties.

background-repeat: no-repeat, no-repeat; background-position: right, left; 

There are several sub-properties you can add to your background images, such as background-repeat and background-position , which we used in the above example. You can even add gradients to a background image.

See what it looks like when we put everything together.

Order Matters

The order that you list your images in matters because of the stacking order. That means the first image listed is nearest to the user, according to the documentation. Then, the next one, and the next, and so on.

We’ve listed two images in the code above. The first image (morocco-blue.png) will be in front of the second (oriental-tiles.png). Both images are the same size and lack opacity, so we only see the first image.

But if we move the second image (oriental-tiles.png) over to the right by 200 pixels, then you can see part of it (the rest remains hidden).

Here’s what it looks like when we put everything together.

When Should You Use Background Image?

There’s a lot to like about the background-image property. But there’s a drawback.

The image may not be accessible to all users, the documentation points out, like those who use screen readers.

That’s because you can’t add textual information to the background-image property. As a result, the image will be missed by screen readers.

Use the background-image property only when you need to add some decoration to your page. Otherwise, use the HTML element if an image has meaning or purpose, as the documentation notes.

That way, you can add text to an image element, using the alt attribute, which describes the image. The provided text will be picked up by screen readers.

 A glass house designed by Ludwig Mies van der Rohe located in Plano, Illinois.

Think of it this way: background-image is a CSS property, and CSS focuses on presentation or style; HTML focuses on semantics or meaning.

When it comes to images, you’ve got options. If an image is needed for decoration, then the background-image property may be a good choice for you.

I write about learning to program and the best ways to go about it (amymhaddad.com).

Источник

CSS background-image Property

The background-image property sets one or more background images for an element.

By default, a background-image is placed at the top-left corner of an element, and repeated both vertically and horizontally.

Tip: The background of an element is the total size of the element, including padding and border (but not the margin).

Tip: Always set a background-color to be used if the image is unavailable.

Default value: none
Inherited: no
Animatable: no. Read about animatable
Version: CSS1 + new values in CSS3
JavaScript syntax: object.style.backgroundImage=»url(img_tree.gif)» Try it

Browser Support

The numbers in the table specify the first browser version that fully supports the property.

CSS Syntax

Property Values

Value Description Demo
url(‘URL‘) The URL to the image. To specify more than one image, separate the URLs with a comma Demo ❯
none No background image will be displayed. This is default
conic-gradient() Sets a conic gradient as the background image. Define at least two colors Demo ❯
linear-gradient() Sets a linear gradient as the background image. Define at least two colors (top to bottom) Demo ❯
radial-gradient() Sets a radial gradient as the background image. Define at least two colors (center to edges) Demo ❯
repeating-conic-gradient() Repeats a conic gradient Demo ❯
repeating-linear-gradient() Repeats a linear gradient Demo ❯
repeating-radial-gradient() Repeats a radial gradient Demo ❯
initial Sets this property to its default value. Read about initial
inherit Inherits this property from its parent element. Read about inherit

More Examples

Example

Sets two background images for the element. Let the first image appear only once (with no-repeat), and let the second image be repeated:

body <
background-image: url(«img_tree.gif»), url(«paper.gif»);
background-repeat: no-repeat, repeat;
background-color: #cccccc;
>

Example

Use different background properties to create a «hero» image:

.hero-image <
background-image: url(«photographer.jpg»); /* The image used */
background-color: #cccccc; /* Used if the image is unavailable */
height: 500px; /* You must set a specified height */
background-position: center; /* Center the image */
background-repeat: no-repeat; /* Do not repeat the image */
background-size: cover; /* Resize the background image to cover the entire container */
>

Example

Sets a linear-gradient (two colors) as a background image for a element:

Example

Sets a linear-gradient (three colors) as a background image for a element:

#grad1 <
height: 200px;
background-color: #cccccc;
background-image: linear-gradient(red, yellow, green);
>

Example

The repeating-linear-gradient() function is used to repeat linear gradients:

#grad1 <
height: 200px;
background-color: #cccccc;
background-image: repeating-linear-gradient(red, yellow 10%, green 20%);
>

Example

Sets a radial-gradient (two colors) as a background image for a element:

Example

Sets a radial-gradient (three colors) as a background image for a element:

#grad1 <
height: 200px;
background-color: #cccccc;
background-image: radial-gradient(red, yellow, green);
>

Example

The repeating-radial-gradient() function is used to repeat radial gradients:

#grad1 <
height: 200px;
background-color: #cccccc;
background-image: repeating-radial-gradient(red, yellow 10%, green 20%);
>

Источник

background-image

Свойство CSS background-image устанавливает одно или несколько фоновых изображений для элемента. Изображения рисуются в слоях контекстов наложения одно поверх другого. Первый слой выводится так, чтобы он был ближе всего к пользователю.

Границы border элемента затем рисуются поверх них, и background-color рисуется под ними. То, как изображения отрисовываются относительно рамки и её границ, определяется CSS-свойствами background-clip и background-origin .

Если указанное изображение не может быть нарисовано (например, когда файл, определённый указанным URI, не может быть загружен), браузеры обрабатывают его так, как если бы оно было значением none .

Примечание: Даже, если изображение непрозрачно и цвет не будет показан при нормальных обстоятельствах, веб-разработчику следует всегда указывать атрибут background-color . Если изображение не может быть загружено —например, в случае отказа сетевого подключения — у элемента будет отображён цветной фон.

Начальное значение none
Применяется к все элементы. Это также применяется к ::first-letter и ::first-line .
Наследуется нет
Обработка значения как указано, но с абсолютными значениями url
Animation type discrete

Синтаксис

background-image: none; background-image: url(http://www.example.com/bck.png); background-image: inherit; 

Значения

Это ключевое слово обозначает отсутствие изображений.

(en-US) обозначает изображение для отображения. Их может быть несколько, разделённых запятыми, поскольку поддерживаетсянесколько фонов (en-US) .

Официальный синтаксис

background-image =
# (en-US)

=
| (en-US)
none

=
| (en-US)
(en-US)

=
url( (en-US) * (en-US) ) | (en-US)
src( (en-US) * (en-US) )

Примеры

Несколько фонов и прозрачность

Обратите внимание, что изображение звезды частично прозрачно и наложено на изображение кошки.

HTML содержимое

div> p class="catsandstars"> This paragraph is full of catsbr />and stars. p> p>This paragraph is not.p> p class="catsandstars"> Here are more cats for you.br />Look at them! p> p>And no more.p> div> 

CSS содержимое

pre, p  font-size: 1.5em; color: #FE7F88; background-color: transparent; > div  background-image: url("mdn_logo_only_color.png"); > p  background-image: none; > .catsandstars  background-image: url("startransparent.gif"), url("catfront.png"); background-color: transparent; > 

Спецификации

Совместимость браузеров

BCD tables only load in the browser

Смотрите также

Found a content problem with this page?

This page was last modified on 11 февр. 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.

Источник

Читайте также:  Java get jvm info
Оцените статью