Как в html сделать фон
Перейти к содержимому

Как в html сделать фон

  • автор:

CSS Background Image – With HTML Example Code

Dionysia Lemonaki

Dionysia Lemonaki

CSS Background Image – With HTML Example Code

What a user sees on a website will impact how good their user experience is. It will also affect how easily they can use the whole site in general.

Adding images to the background of certain parts of a website is often more visually appealing and interesting than just changing the background-color.

Modern browsers support a variety of image file types like .jpg , .png , .gif , and .svg .

This article explains how to add images to your HTML code and how to then fine-tune them to look better.

Background Image Syntax

The first step is to make sure you create an assets directory (folder) to hold the images you want to use in your project.

For example we can create an images folder in the project we are working on and add an image called sunset.png that we want to use.

The background-image CSS property allows you to then place the image behind any HTML element you wish.

This could either be the whole page (by using the body selector in CSS which targets the <body> element in our HTML), or just a standalone specific part of the page such as a section element like in the example below.

To add a background-image to a section tag in your .css file, write the following code:

Let’s discuss what’s going on here in detail:

  • section specifies the tag you want to add the image to.
  • url() is used to tell CSS where our image is located.
  • Inside the parentheses, «images/sunset.png» is the path to the image. This lets the browser know what URL to pull.
  • The path in this example is called a relative path which means it is a local file, relative to our project and to our current working directory and is not a web address. To add images we can also use an absolute path, which is a full web address and starts with a domain URL ( http://www. ).
  • Using quotes is a good habit but we can omit them, so background-image: url(images/sunset.png) works the same.
  • Don’t forget the semicolon!

How to Stop Background Repeat

When you apply a background image to an element, by default it will repeat itself.

If the image is smaller than the tag of which it’s the background, it will repeat in order to fill in the tag.

How do we stop this from happening?

The background-repeat property takes in 4 values and we are able to change the direction in which the image repeats, or stop the image from repeating itself all together.

This is the default value if we don’t give the background-repeat property a value. In this case the image is repeated both horizontally and vertically so in both x-direction and y-direction respectively until it fills the space.

Screenshot-2021-07-20-at-9.10.06-PM

Screenshot-2021-07-20-at-9.11.39-PM

The no-repeat value stops the image from repeating itself from all directions. The image is only shown once.

This value repeats the image only horizontally on the page. The image is repeated across the page, in the x-direction . The x-direction in math is from the left to the right.

This value repeats the image only vertically on the page. The image is repeated down the page ,in the y-direction . The y-direction in math is from top to bottom.

How to Set Background Position

After adding a background image and stopping it from repeating, we are able to further control how it looks within the background of the tag by improving its position.

We’ll use the background-position property to do this.

The selector takes in two values. The first one is for the horizontal position, or x-direction (how far across the tag). The second one is for the vertical position, or y-direction (how far down the tag).

The values can be units, like a pair of pixels:

This will move the image 20px across and 30px down the containing tag.

Instead of pixels we can use a set of keywords like right, left, top, down, or center to place the image at the right, left, top, down, or center of the tag.

This places the image at the right hand side of the center of the tag.

Screenshot-2021-07-21-at-9.02.55-AM

If we wanted to center it both horizontally and vertically, we would do the following:

Screenshot-2021-07-21-at-9.07.41-AM

To position an image with finer detail, it is worth mentioning that we can use percentages.

This positions the image 20% across the tag and 40% down the tag.

So far we have seen values used in combination, but we can also just specify one value like background-position: 20px; or background-position: center; or background-position: 20%; , which applies it to both directions.

How to Resize a Background Image

To control the size of the background image we can use the background-size property.

Again, like the previous properties mentioned, it takes in two values. One for the horizontal (x) size and one for the vertical (y) size.

We can use pixels, like so:

If we do not know the exact width of the container we are storing the image in, there is a set of specific values we can give the property.

  • background-size: cover; resizes the background image so it covers up the whole tag’s background space no matter the width of the tag. If the image is too big and has a larger ratio to the tag it is in, this means the image will get stretched and therefore cropped at its edges.
  • background-size: contain; contains the image, as the name suggests. It will make sure the whole image is shown in the background without cropping out any of it. If the image is much smaller than the tag there will be space left empty which will make it repeat to fill it up, so we can use the background-repeat: no-repeat; rule we mentioned earlier.

Screenshot-2021-07-21-at-9.18.15-AM

The rule background-size:cover; in this case will crop of parts of the image

When we change it to background-size:contain; we see that the image shrinks to fit the section tag.

Screenshot-2021-07-21-at-9.18.49-AM

How to Use the Background Attachment Property

With the background-attachment property we can control where the background image is attached, meaning if the image is fixed or not to the browser.

The default value is background-attachment: scroll; , where the background image stays with its tag and follows the natural flow of the page by scrolling up and down as we scroll up and down.

The second value the property can have is background-attachement: fixed; .
This makes the background image stay in the same postion, fixed to the page and fixed on the browser’s viewport. This creates a parallax effect which you can see an example of here:

See the Pen by Dionysia Lemonaki (@deniselemonaki) on CodePen.

Background Gradients

A different use case for the background-image property is for telling the browser to create a gradient.

The background-image in this case does not have a URL, but a linear-gradient instead.

The simplest way to do this is to specify the angle. This controls the direction of the gradient and how to colors will blend. Lastly add two colors that you want blended together in a gradient for the tag’s background.

A gradient that goes from top to bottom and from black to white is:

The most common degrees used for gradients are:

  • 0deg from top to bottom
  • 90deg from left to right
  • 180deg from bottom to top
  • 270deg from right to left

The above degrees each correspond with to top , to right , to bottom and to left , respectively.

See the Pen by Dionysia Lemonaki (@deniselemonaki) on CodePen.

Instead of keyword colors we can use hex colors to be more particular and have a wider range of options:

See the Pen by Dionysia Lemonaki (@deniselemonaki) on CodePen.

We can also include more than two colors in a gradient, creating different affects and color schemes.

Conclusion

This marks the end of our introduction to the basic syntax of the background-image property.

From here the possibilities are endless and leave room for a lot of creative expression. These effects help the user have a pleasant experience when visiting your website.

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 <style> element, in the <head> section:

Example

Specify the background image in the <style> 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 <body> 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.

Как сделать фон в html и CSS?

В этой статье я покажу несколько вариантов как сделать фон в html и CSS. Думаю, вы согласитесь, что фон играет одну из самых важных ролей в дизайне любого сайта? От него зависит читабельность текста и его общее оформление.

Навигация по статье:

Как в html сделать фон в виде цвета или картинки?

Вы можете задавать фон блока или всей страницы с использованием различных вариантов:

  • при помощи цвета,
  • использовать изображение,
  • градиентный фон,
  • использовать сразу несколько вариантов (например, картинка + цвет или несколько картинок сразу).

Введу того что HTML не особо предназначен для визуального оформления страницы, в с помощью HTML можно сделать только фон в виде цвета или изображения. Для использования остальных вариантов создания фона нам не обойтись без помощи CSS. Но обо всём по порядку.

Чтобы в html сделать фон нам понадобится атрибуты bgcolor и background.

Для того чтобы в HTML сделать фон в виде цвета нужно к тегу для которого нам нужно задать фон дописать атрибут bgcolor

Чтобы сделать фон в виде изображения используем background и в кавычках указываем путь к файлу с картинкой.

Как сделать фон в CSS?

Как я уже писала выше мы можем использовать разные варианты задания фона и для всех их нам понадобится свойство background с разными значениями. Для того чтобы его использовать нам нужно сделать следующее:

    1. В HTML коде присвоить элементу, для которого мы хотим задать цвет определённый класс или использовать атрибут style. Мне больше нравится вариант с классом, поэтому в первую очередь покажу его.

Как сделать фон в виде цвета в CSS?

Для задания цвета фона мы можем использовать несколько форматов:

    1. Кодовое название цвета

Уровень прозрачности задаётся в виде десятичного значения от 0 до 1, где 0 – полностью прозрачный, а 1 – не прозрачный.

Уровень прозрачности

Так же вы можете воспользоваться вот этим инструментом для подбора нужного цвета и определения его кода. Просто водите мышкой по палитре, подбираете цвет и справа отображается его значение в шестнадцатеричном формате (HEX) и в формате rgb.

Как сделать фон в виде картинки в CSS?

Для этого нам нужно будет:

  1. 1. К себе на сайт в определённую папку с картинками загрузить изображение, которое мы хотим использовать в качестве фона.
  2. 2. Задать его в CSS

В скобочках указываем путь к картинке.

Так же если изображение у вас небольшое то будьте готовы увидеть такую картину:

Не подходящий размер

Вы можете отключить повторение фона для маленьких изображений, дописав no-repeat:

Так же можно сделать чтобы он повторялся только по горизонтали:

Или только по вертикали:

Кроме того мы можем управлять расположением фонового изображения для элемента. Для этого нам нужно дописать следующе:

  • top – для выравнивание по верхнему краю
  • bottom — для выравнивания по нижнему краю
  • left – выравниваем по левому краю
  • right – по правому
  • center – выравниваем по центру (можно использовать как для выравнивания по горизонтали так по вертикали)

Так же можно сочетать эти выравнивания.

Как растянуть фоновое изображение под размер элемента?

По умолчанию фоновое изображение не подстраивается под размер элемента. В эпоху адаптивных дизайнов это доставляет много неудобств. Для решения этой проблемы можно использовать свойство background-size.

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

Как изменить расположение фона внутри элемента?

Кроме описанных выше значений top, bottom, left, right и center мы так же можем использовать значения в пикселях, процентах и em чтобы выставить фоновую картинку так как нам нужно.

Добавить комментарий

Ваш адрес email не будет опубликован. Обязательные поля помечены *