Html css background image as link

Как добавить изображение фоном. Свойство background-image

background-image позволяет добавить изображение в качестве фона для выбранного элемента. Фоновое изображение может быть любого типа и повторяться или масштабироваться в зависимости от настроек.

Значения

  • url(‘путь_к_изображению’) — указывает путь к изображению. Вы можете указать относительный путь к изображению на вашем сервере или абсолютный URL для изображения в интернете.
  • none — значение по умолчанию, где нет фона. Если не хотите использовать изображение в качестве фона, вы можете установить background-image: none; .
  • linear-gradient() , radial-gradient() , repeating-linear-gradient() , repeating-radial-gradient() — создают градиент фона без использования изображений. Можно определить цветовую палитру и ориентацию градиента.

Повторное изображение

background-repeat: repeat; — значение по умолчанию, изображение повторяется по горизонтали и вертикали. Изображение будет заполнять фон элемента, повторяясь при необходимости.

background-repeat: repeat-x; — повторяется только по горизонтали.

background-repeat: repeat-y; — повторяется только по вертикали.

background-repeat: no-repeat; — отображается только один раз без повторения.

Размер изображения

background-size: auto; — отображается в своём естественном размере.

background-size: cover; — масштабируется так, чтобы полностью заполнить фон элемента, возможно, обрезая его.

background-size: contain; — масштабируется так, чтобы полностью поместиться в фон элемента без искажений. Белые полосы могут появиться по краям фона, если пропорции изображения и фона не совпадают.

Наследование

Свойство background-image не наследуется дочерними элементами. Каждый элемент должен самостоятельно задавать фоновое изображение.

Примеры использования

Добавление изображения на фон определённого элемента

Добавление повторяющегося изображения на фон элемента

Добавление градиента на фон

Нюансы использования

  • Фоновые картинки не будут автоматически масштабироваться под размеры родительского элемента. Если размеры картинки и родительского элемента не совпадают, то картинка обрежется или начнёт повторяться.
  • Если задать цвет фона и background-image для одного элемента, то картинка будет отображаться поверх цвета фона.
Читайте также:  Running java programs on android

⭐ Поддержка браузерами свойства background-image

Материалы по теме

«Доктайп» — журнал о фронтенде. Читайте, слушайте и учитесь с нами.

Источник

Associating icons with links can in my opinion be a powerful design device. With a small amount of CSS it is simple to add icons into your links.

To apply an icon to links in CSS you use background-image. Although you should use icons on links sparingly icons can greatly improve the usability of a site. In this example we have a link that goes to a journal entry page. Make an icon using Illustrator, Photoshop or your favorite imaging software. Make sure that it relates well to the size of the text it appears next to. Here I’ve made a simple pencil:

The Markup ¶

In this example we have a simple link within a div

div id="example-link">  a href="#">Link to journal articlea> div> 

The CSS ¶

#example-link a   padding-left: 15px;  background: url(/images/examples/bglinks/pencil_icon.gif) 3px 1px no-repeat; > 

Explanation: ¶

Padding left — This moves the text away from the image. Depending on the width of your image you will need more or less padding

Background — This has the rules associated with the the background image

  • url(/images/examples/bglinks/pencil_icon.gif) — This is the path the image you want to be your icon.
  • 3px 1px — These values position the background image. The first value is the background image’s distance from the left of the a tag, the second is the distance from the top of the a tag.
  • No-repeat tells the browser only to show the image once.

The code in action ¶

A simple icon applied to a link using CSS. (If you are reading this in a newsreader you won’t see the image)

Tags

Can you help make this article better? You can edit it here and send me a pull request.

See Also

  • Writing good XHTML and CSS Part 2
    Oct 7, 2006
    The second in a series of good practices for writing XHTML and CSS looking at writing clean, maintainable code and dealing with browser hell problems.
  • Preparing for IE7 — Limiting CSS Hacks
    Sep 28, 2006
    Internet Explorer 7 is just around the corner and there have been warnings from Microsoft that existing hacks will break layouts in IE7. By limiting the use of hacks your CSS can be both backwards and forwards compliant.
  • Writing good XHTML and CSS Part 1
    Sep 26, 2006
    In two articles I’m going to outline my opinion on what you need to understand and write high quality XTHML and CSS. The articles will focus on producing code that stands up to the rigors of the web and future proofs code. The articles are aimed at coders starting out and looking to get to grips with writing professional front end code. Of course if you don’t agree with something the comments box is there for you to add your opinion. In part 1 I’m going to look at what you need to get off the ground.

Источник

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).

Источник

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