Сss3 backgrounds

Images

SlideshowSlideshow GalleryModal ImagesLightboxResponsive Image GridImage GridTab GalleryImage Overlay FadeImage Overlay SlideImage Overlay ZoomImage Overlay TitleImage Overlay IconImage EffectsBlack and White ImageImage TextImage Text BlocksTransparent Image TextFull Page ImageForm on ImageHero ImageBlur Background ImageChange Bg on ScrollSide-by-Side ImagesRounded ImagesAvatar ImagesResponsive ImagesCenter ImagesThumbnailsBorder Around ImageMeet the TeamSticky ImageFlip an ImageShake an ImagePortfolio GalleryPortfolio with FilteringImage ZoomImage Magnifier GlassImage Comparison Slider

More Examples

Example

How to position a background-image to be centered at top:

body
{
  background-image: url(‘w3css.gif’);
 
background-repeat: no-repeat;
  background-attachment: fixed;
 
background-position: center top;
}

Example

How to position a background-image to be bottom right:

body
{
 
background-image: url(‘w3css.gif’);
 
background-repeat: no-repeat;
 
background-attachment: fixed;
 
background-position: bottom right;
}

Example

How to position a background-image using percent:

body
{
  background-image: url(‘w3css.gif’);
 
background-repeat: no-repeat;
 
background-attachment: fixed;
 
background-position: 50% 50%;
}

Example

How to position a background-image using pixels:

body
{
  background-image: url(‘w3css.gif’);
 
background-repeat: no-repeat;
 
background-attachment: fixed;
  background-position: 50px 150px;
}

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 */}

CSS Reference

CSS ReferenceCSS Browser SupportCSS SelectorsCSS FunctionsCSS Reference AuralCSS Web Safe FontsCSS Font FallbacksCSS AnimatableCSS UnitsCSS PX-EM ConverterCSS ColorsCSS Color ValuesCSS Default ValuesCSS Entities

CSS Properties

align-content
align-items
align-self
all
animation
animation-delay
animation-direction
animation-duration
animation-fill-mode
animation-iteration-count
animation-name
animation-play-state
animation-timing-function

backface-visibility
background
background-attachment
background-blend-mode
background-clip
background-color
background-image
background-origin
background-position
background-repeat
background-size
border
border-bottom
border-bottom-color
border-bottom-left-radius
border-bottom-right-radius
border-bottom-style
border-bottom-width
border-collapse
border-color
border-image
border-image-outset
border-image-repeat
border-image-slice
border-image-source
border-image-width
border-left
border-left-color
border-left-style
border-left-width
border-radius
border-right
border-right-color
border-right-style
border-right-width
border-spacing
border-style
border-top
border-top-color
border-top-left-radius
border-top-right-radius
border-top-style
border-top-width
border-width
bottom
box-decoration-break
box-shadow
box-sizing
break-after
break-before
break-inside

caption-side
caret-color
@charset
clear
clip
clip-path
color
column-count
column-fill
column-gap
column-rule
column-rule-color
column-rule-style
column-rule-width
column-span
column-width
columns
content
counter-increment
counter-reset
cursor

direction
display
empty-cells
filter
flex
flex-basis
flex-direction
flex-flow
flex-grow
flex-shrink
flex-wrap
float
font
@font-face
font-family
font-feature-settings
font-kerning
font-size
font-size-adjust
font-stretch
font-style
font-variant
font-variant-caps
font-weight

grid
grid-area
grid-auto-columns
grid-auto-flow
grid-auto-rows
grid-column
grid-column-end
grid-column-gap
grid-column-start
grid-gap
grid-row
grid-row-end
grid-row-gap
grid-row-start
grid-template
grid-template-areas
grid-template-columns
grid-template-rows

hanging-punctuation
height
hyphens
@import
isolation
justify-content
@keyframes
left
letter-spacing

line-height
list-style
list-style-image
list-style-position
list-style-type

margin
margin-bottom
margin-left
margin-right
margin-top
max-height
max-width
@media
min-height
min-width
mix-blend-mode

object-fit
object-position
opacity
order
outline
outline-color
outline-offset
outline-style
outline-width
overflow
overflow-x
overflow-y

padding
padding-bottom
padding-left
padding-right
padding-top
page-break-after
page-break-before
page-break-inside
perspective
perspective-origin
pointer-events
position
quotes

resize
right

scroll-behavior

tab-size
table-layout
text-align
text-align-last
text-decoration
text-decoration-color
text-decoration-line
text-decoration-style
text-indent
text-justify
text-overflow
text-shadow
text-transform
top

transform
transform-origin
transform-style
transition
transition-delay
transition-duration
transition-property
transition-timing-function

unicode-bidi
user-select

vertical-align
visibility

white-space
width
word-break
word-spacing
word-wrap
writing-mode

z-index

Множественные фоновые изображения

Я знаю, что многим не терпится увидеть программную реализацию теоретического материала, но подождите еще немного. Для начала я хочу рассказать и об этой технологии, а потом приведу пример с использованием большинства описанных свойств.

Итак, что же такое множественные фоны? Это прекрасная возможность отображать в окне браузера сразу несколько изображений в виде фона. Такой прием может пригодиться:

  • Для ускорения загрузки веб-страниц, ведь маленькие изображения грузятся быстрее тяжелых графических документов;
  • Для определения разных слоев для сайта;
  • Для создания комплексного фона, собранного из разных частей и т.д.

Вот теперь пришел звездный час практической части. После запуска ниже прикрепленного примера на экране отобразится самолет, который летит по небу. Подчеркну, что самолет – это изображение с прозрачным фоном, а небо – это фоновая картинка.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
<!DOCTYPE html>
<html>
 <head>
  <meta charset="utf-8">
  <title>Растягиваемый фон</title>
  <style>
   body {
    background-image: url(http://img-fotki.yandex.ru/get/5642/16969765.110/0_704d0_8e3d9602_orig.png), url(http://luxfon.com/images/201203/luxfon.com_5408.jpg);
     background-position: center center, center center;
    background-repeat: no-repeat, no-repeat;
    background-size: 30%, cover;
    background-attachment: fixed, fixed;
   }
  </style>
 </head>
 <body>
 </body>
</html>

Аналогично будет выглядеть и следующая реализация поставленной задачи:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
<!DOCTYPE html>
<html>
 <head>
  <meta charset="utf-8">
  <title>Растягиваемый фон</title>
  <style>
 
  body {
    background: url(http://img-fotki.yandex.ru/get/5642/16969765.110/0_704d0_8e3d9602_orig.png) center center no-repeat fixed,  
               url(http://luxfon.com/images/201203/luxfon.com_5408.jpg) center center no-repeat fixed;
     background-size: 30%, cover;
   }
  </style>
 </head>
 <body>
 </body>
</html>

Ну вот я объяснил вам основные механизмы управления рисунками заднего фона. Некоторые могут подумать: «А где же описание адаптивных изображений?». Это правильный вопрос и тянет на отдельную статью, которая, кстати, выйдет очень скоро.

А пока настало время прощаться. Надеюсь публикация вам понравилась. Буду рад новым подписчикам! Пока-пока!

Прочитано: 186 раз

Background Images

Background images can also respond to resizing and scaling.

Here we will show three different methods:

1. If the property is set to «contain», the
background
image will scale, and try to fit the content area. However, the image will keep its aspect ratio (the proportional relationship
between the image’s width and height):

Here is the CSS code:

Example

div {  width: 100%;  height: 400px; 
background-image: url(‘img_flowers.jpg’);  background-repeat: no-repeat;  background-size: contain;  border: 1px solid red;}

2. If the property is set to «100% 100%», the background image will stretch to cover the entire content area:

Here is the CSS code:

Example

div {  width: 100%;  height: 400px; 
background-image: url(‘img_flowers.jpg’); 
background-size: 100% 100%;  border: 1px solid red;}

3. If the property is set to «cover», the background image will scale
to cover the entire content area. Notice that the «cover» value keeps the aspect
ratio, and some part of the background image may be
clipped:

Here is the CSS code:

Example

div {  width: 100%;  height: 400px; 
background-image: url(‘img_flowers.jpg’);  background-size: cover;  border: 1px solid red;}

CSS Tutorial

CSS HOMECSS IntroductionCSS SyntaxCSS SelectorsCSS How ToCSS CommentsCSS Colors
Colors
RGB
HEX
HSL

CSS Backgrounds
Background Color
Background Image
Background Repeat
Background Attachment
Background Shorthand

CSS Borders
Borders
Border Width
Border Color
Border Sides
Border Shorthand
Rounded Borders

CSS Margins
Margins
Margin Collapse

CSS PaddingCSS Height/WidthCSS Box ModelCSS Outline
Outline
Outline Width
Outline Color
Outline Shorthand
Outline Offset

CSS Text
Text Color
Text Alignment
Text Decoration
Text Transformation
Text Spacing
Text Shadow

CSS Fonts
Font Family
Font Web Safe
Font Style
Font Size
Font Google
Font Shorthand

CSS IconsCSS LinksCSS ListsCSS Tables
Table Borders
Table Size
Table Alignment
Table Style
Table Responsive

CSS DisplayCSS Max-widthCSS PositionCSS OverflowCSS Float
Float
Clear
Float Examples

CSS Inline-blockCSS AlignCSS CombinatorsCSS Pseudo-classCSS Pseudo-elementCSS OpacityCSS Navigation Bar
Navbar
Vertical Navbar
Horizontal Navbar

CSS DropdownsCSS Image GalleryCSS Image SpritesCSS Attr SelectorsCSS FormsCSS CountersCSS Website LayoutCSS UnitsCSS Specificity

Transparency using RGBA

If you do not want to apply opacity to child elements, like in our example above, use RGBA color values.
The following example sets the opacity for the background color and not the text:

100% opacity

60% opacity

30% opacity

10% opacity

You learned from our CSS Colors Chapter, that you can use RGB as a color value. In addition to RGB,
you can use an RGB color value with an alpha channel (RGBA) — which specifies the opacity for a color.

An RGBA color value is specified with: rgba(red, green, blue, alpha). The
alpha parameter is a number between 0.0 (fully transparent) and 1.0 (fully opaque).

Tip: You will learn more about RGBA Colors in our CSS Colors Chapter.

CSS background — Shorthand property

To shorten the code, it is also possible to specify all the background properties in one
single property. This is called a shorthand property.

Instead of writing:

body {  background-color: #ffffff;  background-image:
url(«img_tree.png»);  background-repeat: no-repeat; 
background-position: right top;}

You can use the shorthand property :

Example

Use the shorthand property to set the background properties in one
declaration:

body {  background: #ffffff url(«img_tree.png») no-repeat right top;}

When using the shorthand property the order of the property values is:

It does not matter if one of the property values is missing, as long as the
other ones are in this order. Note that we do not use the background-attachment property in the examples above, as it does not have a value.

All CSS Background Properties

Property Description
background Sets all the background properties in one declaration
background-attachment Sets whether a background image is fixed or scrolls with the rest of the page
background-clip Specifies the painting area of the background
background-color Sets the background color of an element
background-image Sets the background image for an element
background-origin Specifies where the background image(s) is/are positioned
background-position Sets the starting position of a background image
background-repeat Sets how a background image will be repeated
background-size Specifies the size of the background image(s)

❮ Previous
Next ❯

CSS Reference

CSS ReferenceCSS Browser SupportCSS SelectorsCSS FunctionsCSS Reference AuralCSS Web Safe FontsCSS Font FallbacksCSS AnimatableCSS UnitsCSS PX-EM ConverterCSS ColorsCSS Color ValuesCSS Default ValuesCSS Entities

CSS Properties

align-content
align-items
align-self
all
animation
animation-delay
animation-direction
animation-duration
animation-fill-mode
animation-iteration-count
animation-name
animation-play-state
animation-timing-function

backface-visibility
background
background-attachment
background-blend-mode
background-clip
background-color
background-image
background-origin
background-position
background-repeat
background-size
border
border-bottom
border-bottom-color
border-bottom-left-radius
border-bottom-right-radius
border-bottom-style
border-bottom-width
border-collapse
border-color
border-image
border-image-outset
border-image-repeat
border-image-slice
border-image-source
border-image-width
border-left
border-left-color
border-left-style
border-left-width
border-radius
border-right
border-right-color
border-right-style
border-right-width
border-spacing
border-style
border-top
border-top-color
border-top-left-radius
border-top-right-radius
border-top-style
border-top-width
border-width
bottom
box-decoration-break
box-shadow
box-sizing
break-after
break-before
break-inside

caption-side
caret-color
@charset
clear
clip
clip-path
color
column-count
column-fill
column-gap
column-rule
column-rule-color
column-rule-style
column-rule-width
column-span
column-width
columns
content
counter-increment
counter-reset
cursor

direction
display
empty-cells
filter
flex
flex-basis
flex-direction
flex-flow
flex-grow
flex-shrink
flex-wrap
float
font
@font-face
font-family
font-feature-settings
font-kerning
font-size
font-size-adjust
font-stretch
font-style
font-variant
font-variant-caps
font-weight

grid
grid-area
grid-auto-columns
grid-auto-flow
grid-auto-rows
grid-column
grid-column-end
grid-column-gap
grid-column-start
grid-gap
grid-row
grid-row-end
grid-row-gap
grid-row-start
grid-template
grid-template-areas
grid-template-columns
grid-template-rows

hanging-punctuation
height
hyphens
@import
isolation
justify-content
@keyframes
left
letter-spacing

line-height
list-style
list-style-image
list-style-position
list-style-type

margin
margin-bottom
margin-left
margin-right
margin-top
max-height
max-width
@media
min-height
min-width
mix-blend-mode

object-fit
object-position
opacity
order
outline
outline-color
outline-offset
outline-style
outline-width
overflow
overflow-x
overflow-y

padding
padding-bottom
padding-left
padding-right
padding-top
page-break-after
page-break-before
page-break-inside
perspective
perspective-origin
pointer-events
position
quotes

resize
right

scroll-behavior

tab-size
table-layout
text-align
text-align-last
text-decoration
text-decoration-color
text-decoration-line
text-decoration-style
text-indent
text-justify
text-overflow
text-shadow
text-transform
top

transform
transform-origin
transform-style
transition
transition-delay
transition-duration
transition-property
transition-timing-function

unicode-bidi
user-select

vertical-align
visibility

white-space
width
word-break
word-spacing
word-wrap
writing-mode

z-index

CSS Tutorial

CSS HOMECSS IntroductionCSS SyntaxCSS SelectorsCSS How ToCSS CommentsCSS Colors
Colors
RGB
HEX
HSL

CSS Backgrounds
Background Color
Background Image
Background Repeat
Background Attachment
Background Shorthand

CSS Borders
Borders
Border Width
Border Color
Border Sides
Border Shorthand
Rounded Borders

CSS Margins
Margins
Margin Collapse

CSS PaddingCSS Height/WidthCSS Box ModelCSS Outline
Outline
Outline Width
Outline Color
Outline Shorthand
Outline Offset

CSS Text
Text Color
Text Alignment
Text Decoration
Text Transformation
Text Spacing
Text Shadow

CSS Fonts
Font Family
Font Web Safe
Font Style
Font Size
Font Google
Font Shorthand

CSS IconsCSS LinksCSS ListsCSS Tables
Table Borders
Table Size
Table Alignment
Table Style
Table Responsive

CSS DisplayCSS Max-widthCSS PositionCSS OverflowCSS Float
Float
Clear
Float Examples

CSS Inline-blockCSS AlignCSS CombinatorsCSS Pseudo-classCSS Pseudo-elementCSS OpacityCSS Navigation Bar
Navbar
Vertical Navbar
Horizontal Navbar

CSS DropdownsCSS Image GalleryCSS Image SpritesCSS Attr SelectorsCSS FormsCSS CountersCSS Website LayoutCSS UnitsCSS Specificity

CSS Tutorial

CSS HOMECSS IntroductionCSS SyntaxCSS SelectorsCSS How ToCSS CommentsCSS Colors
Colors
RGB
HEX
HSL

CSS Backgrounds
Background Color
Background Image
Background Repeat
Background Attachment
Background Shorthand

CSS Borders
Borders
Border Width
Border Color
Border Sides
Border Shorthand
Rounded Borders

CSS Margins
Margins
Margin Collapse

CSS PaddingCSS Height/WidthCSS Box ModelCSS Outline
Outline
Outline Width
Outline Color
Outline Shorthand
Outline Offset

CSS Text
Text Color
Text Alignment
Text Decoration
Text Transformation
Text Spacing
Text Shadow

CSS Fonts
Font Family
Font Web Safe
Font Style
Font Size
Font Google
Font Shorthand

CSS IconsCSS LinksCSS ListsCSS Tables
Table Borders
Table Size
Table Alignment
Table Style
Table Responsive

CSS DisplayCSS Max-widthCSS PositionCSS OverflowCSS Float
Float
Clear
Float Examples

CSS Inline-blockCSS AlignCSS CombinatorsCSS Pseudo-classCSS Pseudo-elementCSS OpacityCSS Navigation Bar
Navbar
Vertical Navbar
Horizontal Navbar

CSS DropdownsCSS Image GalleryCSS Image SpritesCSS Attr SelectorsCSS FormsCSS CountersCSS Website LayoutCSS UnitsCSS Specificity

Управление позицией фонового изображения

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

Значение Описание
left topleft centerleft bottomright topright centerright bottomcenter topcenter centercenter bottom Задает положение изображения. Первое значение-горизонтальное положение, а второе значение вертикальное. Если вы указываете только одно ключевое слово, другое значение будет «center»
x% y% Задает положение изображения. Первое значение — горизонтальное положение, а второе значение вертикальное. Левый верхний угол имеет 0% 0% (это значение по умолчанию). В правом нижнем углу 100% 100%. Если указано только одно значение, то другое значение будет 50%.
x y Задает положение изображения. Первое значение — горизонтальное положение, а второе значение вертикальное. Левый верхний угол имеет 0 0. Значения могут быть в пикселях, или других единицах измерения CSS. Если указано только одно значение, то другое значение будет 50%. Вы можете совместно использовать проценты и единицы измерения.

Рассмотрим пример использования этого свойства:

<!DOCTYPE html>
<html>
<head>
	<title>Пример позиционирования фонового изображения</title>
<style> 
div {
display: inline-block; /* устанавливаем, что элементы становятся блочно-строчными (чтобы выстроились в линейку) */
background-image: url("smile_bg.png"); /* указываем путь к файлу изображения, которое будет использоваться как задний фон */
background-repeat: no-repeat; /**/
width: 100px; /* устанавливаем ширину элемента */
height: 100px; /* устанавливаем высоту элемента */
border: 1px solid; /* устанваливаем сплошную границу размером 1 пиксель */
margin: 10px; /* устанавливаем внешние отступы со всех сторон */
text-align: center; /* выравниваем текст по центру */
line-height: 60px; /* указываем высоту строки */
background-color: azure; /* задаем цвет заднего фона */
}
.leftTop {background-position: left top;} /* задаем позицию ключевыми словами */
.leftCenter {background-position: left center;} /* задаем позицию ключевыми словами */
.leftBottom {background-position: left bottom;} /* задаем позицию ключевыми словами */
.rightTop {background-position: right top;} /* задаем позицию ключевыми словами */
.rightCenter {background-position: right center;} /* задаем позицию ключевыми словами */
.rightBottom {background-position: right bottom;} /* задаем позицию ключевыми словами */
.centerTop {background-position: center top;} /* задаем позицию ключевыми словами */
.centerCenter {background-position: center center;} /* задаем позицию ключевыми словами */
.centerBottom {background-position: center bottom;} /* задаем позицию ключевыми словами */
.userPosition {background-position: 20px 75%;} /* задаем позицию по горизонтали в пикселях, а по вертикали в процентах */
</style>
</head>
	<body>
		<div class = "leftTop">left top</div>
		<div class = "leftCenter">left center</div>
		<div class = "leftBottom">left bottom</div>
		<div class = "rightTop">right top</div>
		<div class = "rightCenter">right center</div>
		<div class = "rightBottom">right bottom</div>
		<div class = "centerTop">center top</div>
		<div class = "centerCenter">center center</div>
		<div class = "centerBottom">center bottom</div>
		<div class = "userPosition">20px 75%</div>
	</body>
</html>

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

Результат нашего примера:

Рис. 117 Пример позиционирования фонового изображения.

Как задать цвет и изображение фона сайта

Для задания цвета фона используют свойство background-color, оно принимает значения в шестнадцатеричном формате цвета, в формате RGB, задание цвета при помощи ключевых слов.

Чтобы использовать в качестве фона сайта изображения, применяют свойство background-image, где указывают ссылку на файл. Можно использовать одновременно и вариант с цветом фона, и с изображением. Тогда изображение накладывается поверх фона определенного цвета.

Теперь поговорим о том, как регулировать повторение фонового изображения, как растянуть его на весь экран и т.д. Свойство, которое отвечает за повтор фона, называется background-repeat. Оно принимает четыре значения. В качестве значения по умолчанию принимается repeat (повторять по вертикали и горизонтали). Три других значения:

  • repeat-x — повторяет изображение по горизонтали
  • repeat-y — повторяет изображение по вертикали
  • no-repeat — не повторяет изображение совсем

Для задания размера фонового изображения сайта используют свойство background-size, оно принимает значения в процентах, пикселях и слово auto. Имеет два значения через пробел. Первое значение отвечает за растяжение по горизонтали, второе по вертикали. Если первое значение задано (например, 100%), а второе значение выставлено auto, то фон по горизонтали растянется на весь размер блока, а по вертикали подгоняет высоту для данной ширины. Есть еще два значения для этого свойства (cover и contain). Cover изменяет размеры изображения так, чтобы блок был полностью закрыт картинкой, а contain так, чтобы картинка поместилась в блок целиком. Cover и contain задаются по одному, через пробел уже ничего писать не нужно.

Пример. Зададим цвет фона, его изображение без повтора и растянем его по ширине и высоте:

Положение фонового изображения, background-position

Немного подробнее остановимся на работе с фоновым изображением, которое не нужно повторять. Для регулирования нахождения этого изображения внутри блока, которому мы задаем фон, используется CSS-свойство background-position. Это свойство принимает два значения через пробел. Первое определяет положение по оси x (горизонтали), второе по оси y (вертикали).

Единицы измерения этих двух величин проценты и пиксели. Еще они принимают значения top, bottom, left, right, center. Значения для оси x, естественно, left, right, center. Значения для оси y — top, bottom, center. Единицы измерения, значения, пиксели и проценты можно комбинировать между собой в произвольном формате. В примере ниже зададим позиции для фонового изображения. В первом случае будет изображение по центру в процентах. Во втором случае изображение в правом нижнем углу блока. В третьем случает изображение сдвинуто на 50 пикселей слева и на 100 пикселей сверху. Пример:

Фиксим фонового изображения, background-attachment

Иногда для создания визуальных эффектов нужно, чтобы фон при прокрутки не уезжал вместе с просмотренной частью страницы, а оставался на месте. Это будет создавать интересный эффект параллакса.

Для фиксации фона используется css-свойство background-attachement. Оно принимает два значения, scroll — значение по умолчанию, прокрутка вместе со всем остальным содержимым, fixed — фон остается на месте при прокрутке.

Transparency using RGBA

If you do not want to apply opacity to child elements, like in our example above, use RGBA color values.
The following example sets the opacity for the background color and not the text:

100% opacity

60% opacity

30% opacity

10% opacity

You learned from our CSS Colors Chapter, that you can use RGB as a color value. In addition to RGB,
you can use an RGB color value with an alpha channel (RGBA) — which specifies the opacity for a color.

An RGBA color value is specified with: rgba(red, green, blue, alpha). The
alpha parameter is a number between 0.0 (fully transparent) and 1.0 (fully opaque).

Tip: You will learn more about RGBA Colors in our CSS Colors Chapter.

More

Fullscreen VideoModal BoxesDelete ModalTimelineScroll IndicatorProgress BarsSkill BarRange SlidersTooltipsDisplay Element HoverPopupsCollapsibleCalendarHTML IncludesTo Do ListLoadersStar RatingUser RatingOverlay EffectContact ChipsCardsFlip CardProfile CardProduct CardAlertsCalloutNotesLabelsCirclesStyle HRCouponList GroupList Without BulletsResponsive TextCutout TextGlowing TextFixed FooterSticky ElementEqual HeightClearfixResponsive FloatsSnackbarFullscreen WindowScroll DrawingSmooth ScrollGradient Bg ScrollSticky HeaderShrink Header on ScrollPricing TableParallaxAspect RatioResponsive IframesToggle Like/DislikeToggle Hide/ShowToggle Dark ModeToggle TextToggle ClassAdd ClassRemove ClassActive ClassTree ViewRemove PropertyOffline DetectionFind Hidden ElementRedirect WebpageZoom HoverFlip BoxCenter VerticallyCenter Button in DIVTransition on HoverArrowsShapesDownload LinkFull Height ElementBrowser WindowCustom ScrollbarHide ScrollbarShow/Force ScrollbarDevice LookContenteditable BorderPlaceholder ColorText Selection ColorBullet ColorVertical LineDividersAnimate IconsCountdown TimerTypewriterComing Soon PageChat MessagesPopup Chat WindowSplit ScreenTestimonialsSection CounterQuotes SlideshowClosable List ItemsTypical Device BreakpointsDraggable HTML ElementJS Media QueriesSyntax HighlighterJS AnimationsJS String LengthJS Default ParametersGet Current URLGet Current Screen SizeGet Iframe Elements

How To Create a Blurry Background Image

Step 1) Add HTML:

Example

<div class=»bg-image»></div><div class=»bg-text»>  <h1>I am
John Doe</h1>  <p>And I’m a Photographer</p></div>

Step 2) Add CSS:

Example

body, html {  height: 100%;}* {  box-sizing: border-box;}
.bg-image {  /* The image used */  background-image: url(«photographer.jpg»);  /* Add the blur effect */  filter: blur(8px);  -webkit-filter:
blur(8px);  /* Full height */  height: 100%;  
/* Center and scale the image nicely */  background-position: center; 
background-repeat: no-repeat;  background-size: cover;}/*
Position text in the middle of the page/image */
.bg-text {  background-color: rgb(0,0,0); /* Fallback color */ 
background-color: rgba(0,0,0, 0.4); /* Black w/opacity/see-through */  color: white; 
font-weight: bold;  border: 3px solid #f1f1f1;  position:
absolute;  top: 50%;  left: 50%;  transform:
translate(-50%, -50%);  z-index: 2;  width: 80%; 
padding: 20px;  text-align: center;}

❮ Previous
Next ❯

More Examples

Example

Sets two background images for the <body> 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 <div> element:

#grad1 {  height: 200px;  background-color: #cccccc;  background-image:
linear-gradient(red, yellow);}

Example

Sets a linear-gradient (three colors) as a background image for a <div> 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 <div> element:

#grad1 {  height: 200px;  background-color: #cccccc;  background-image:
radial-gradient(red, yellow);}

Example

Sets a radial-gradient (three colors) as a background image for a <div> 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-repeat или универсального background. Есть три значения:

  • no-repeat — фон не повторяется; применяется для простого добавления единственной картинки;
  • repeat-x — фон повторяется по горизонтали;
  • repeat-y — фон повторяется по вертикали.

Рассмотрим вертикальный бесшовный фон — при повторении картинки по вертикали между отдельными фрагментами не заметно стыков и фоновый рисунок выглядит цельным. Предварительно следует подготовить фоновое изображение, которое должно удовлетворять ряду условий:

  • занимать по высоте не меньше 20–30 пикселей;
  • при стыковке с аналогичным фрагментом изображения по вертикали не должно быть видимых стыков.

Поясним про высоту фоновой картинки. Если сделать изображение слишком узким (2–3 пикселя), то при отображении фона эффект его появления будет виден невооружённым глазом. Увеличение высоты позволяет замостить фон элемента быстро и незаметно.

В качестве образца фона возьмём узор, показанный на рис. 2.

Рис. 2. Фоновая картинка

В примере 2 показано добавление фона на веб-странице с повторением его по вертикали. Чтобы текст не выводился поверх рисунка к селектору body добавлено поле слева.

Пример 2. Повторение фона по вертикали

<!DOCTYPE html>
<html>
<head>
<meta charset=»utf-8″>
<title>Повторение фона</title>
<style>
body {
padding-left: 80px; /* Поле слева */
background:
url(/example/image/pattern-left.png) repeat-y; /* Путь к графическому файлу и
повторение фона по вертикали */
}
</style>
</head>
<body>
<p>Человек должен уметь иногда посмеяться над собой, иначе
он сойдёт с ума. Об этом, к сожалению, знают немногие,
поэтому в мире так много сумасшедших.</p>
<p>Рафаэль Сабатини</p>
</body>
</html>

Результат данного примера показан на рис. 3.

Рис. 3. Вид фона, повторяющегося по вертикали

Аналогично делается и повторение по горизонтали. Предварительно готовим подходящее изображение, затем добавляем его фоном к элементу через background и включаем повторение repeat-x (пример 3).

Пример 3. Повторение фона по горизонтали

<!DOCTYPE html>
<html>
<head>
<meta charset=»utf-8″>
<title>Повторение фона</title>
<style>
.strip {
background: url(/example/image/strip.png) repeat-x; /* Параметры фона */
border-radius: 10px; /* Радиус скругления */
height: 30px; /* Высота элемента */
}
</style>
</head>
<body>
<div class=»strip»></div>
</body>
</html>

Результат данного примера показан на рис. 4.

Рис. 4. Вид фона, повторяющегося по горизонтали

More Examples

Example

Specify the size of a background image with percent:

#example1 {  background: url(mountain.jpg);  background-repeat: no-repeat;  background-size: 100%
100%;}
#example2 {  background: url(mountain.jpg);  background-repeat: no-repeat;  background-size: 75%
50%;}

Example

Specify the size of a background image with «cover»:

#example1 {  background: url(mountain.jpg); 
background-repeat: no-repeat;  background-size: cover;
}

Example

Specify the size of a background image with «contain»:

#example1 {  background: url(mountain.jpg);  background-repeat: no-repeat;
  background-size:
contain;}

Example

Here we have two background images. We specify the size of the first background image with «contain»,
and the second background-image with «cover»:

#example1 {  background: url(img_tree.gif), url(mountain.jpg);
 
background-repeat: no-repeat;  background-size:
contain, cover;}

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 */}

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

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

Adblock
detector