Css и множественный фон

Menus

Icon BarMenu IconAccordionTabsVertical TabsTab HeadersFull Page TabsHover TabsTop NavigationResponsive TopnavNavbar with IconsSearch MenuSearch BarFixed SidebarSide NavigationResponsive SidebarFullscreen NavigationOff-Canvas MenuHover Sidenav ButtonsSidebar with IconsHorizontal Scroll MenuVertical MenuBottom NavigationResponsive Bottom NavBottom Border Nav LinksRight Aligned Menu LinksCentered Menu LinkEqual Width Menu LinksFixed MenuSlide Down Bar on ScrollHide Navbar on ScrollShrink Navbar on ScrollSticky NavbarNavbar on ImageHover DropdownsClick DropdownsCascading DropdownDropdown in TopnavDropdown in SidenavResp Navbar DropdownSubnavigation MenuDropupMega MenuMobile MenuCurtain MenuCollapsed SidebarCollapsed SidepanelPaginationBreadcrumbsButton GroupVertical Button GroupSticky Social BarPill NavigationResponsive Header

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

CSS background-clip Property

The CSS property specifies the painting area of the background.

The property takes three different values:

  • border-box — (default) the background is painted to the outside edge of the border
  • padding-box — the background is painted to the outside edge of the padding
  • content-box — the background is painted within the content box

The following example illustrates the property:

Example

#example1
{
  border: 10px dotted black; 
padding: 35px;  background: yellow; 
background-clip: content-box;}

CSS Advanced Background Properties

Property Description
background A shorthand property for setting all the background properties in one declaration
background-clip Specifies the painting area of the background
background-image Specifies one or more background images for an element
background-origin Specifies where the background image(s) is/are positioned
background-size Specifies the size of the background image(s)

❮ Previous
Next ❯

Firefox

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 Пример позиционирования фонового изображения.

CSS Multiple Backgrounds

CSS allows you to add multiple background images for an element, through the
property.

The different background images are separated by commas, and the images are
stacked on top of each other, where the first image is closest to the viewer.

The following example has two background images, the first image is a flower
(aligned to the bottom and right) and the second image is a paper background (aligned to the top-left corner):

#example1 {  background-image: url(img_flwr.gif), url(paper.gif);  background-position: right bottom, left top;  background-repeat: no-repeat, repeat;}

Multiple background images can be specified using either the individual
background properties (as above) or the shorthand property.

The following example uses the shorthand property (same result as
example above):

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 Advanced

CSS Rounded CornersCSS Border ImagesCSS BackgroundsCSS ColorsCSS Gradients
Linear Gradients
Radial Gradients

CSS Shadows
Shadow Effects
Box Shadow

CSS Text EffectsCSS Web FontsCSS 2D TransformsCSS 3D TransformsCSS TransitionsCSS AnimationsCSS TooltipsCSS Style ImagesCSS object-fitCSS ButtonsCSS PaginationCSS Multiple ColumnsCSS User InterfaceCSS Variables
The var() Function
Overriding Variables
Variables and JavaScript
Variables in Media Queries

CSS Box SizingCSS Media QueriesCSS MQ ExamplesCSS Flexbox
CSS Flexbox
CSS Flex Container
CSS Flex Items
CSS Flex Responsive

Menus

Icon BarMenu IconAccordionTabsVertical TabsTab HeadersFull Page TabsHover TabsTop NavigationResponsive TopnavNavbar with IconsSearch MenuSearch BarFixed SidebarSide NavigationResponsive SidebarFullscreen NavigationOff-Canvas MenuHover Sidenav ButtonsSidebar with IconsHorizontal Scroll MenuVertical MenuBottom NavigationResponsive Bottom NavBottom Border Nav LinksRight Aligned Menu LinksCentered Menu LinkEqual Width Menu LinksFixed MenuSlide Down Bar on ScrollHide Navbar on ScrollShrink Navbar on ScrollSticky NavbarNavbar on ImageHover DropdownsClick DropdownsCascading DropdownDropdown in TopnavDropdown in SidenavResp Navbar DropdownSubnavigation MenuDropupMega MenuMobile MenuCurtain MenuCollapsed SidebarCollapsed SidepanelPaginationBreadcrumbsButton GroupVertical Button GroupSticky Social BarPill NavigationResponsive Header

CSS Background Size

The CSS property allows you to specify the size of background images.

The size can be specified in lengths, percentages, or by using one of the two
keywords: contain or cover.

The following example resizes a background image to much smaller than the original image (using pixels):

Lorem Ipsum Dolor

Lorem ipsum dolor sit amet, consectetuer adipiscing elit, sed diam nonummy nibh euismod tincidunt ut laoreet dolore magna aliquam erat volutpat.

Ut wisi enim ad minim veniam, quis nostrud exerci tation ullamcorper suscipit lobortis nisl ut aliquip ex ea commodo consequat.

Here is the code:

Example

#div1
{
 
background: url(img_flower.jpg);
  background-size: 100px 80px;  background-repeat: no-repeat;
}

The two other possible values for are
and .

The keyword scales the background image to be as large as possible
(but both its width and its height must fit inside the content area). As such, depending on the proportions of the background
image and the background positioning area, there may be some areas of
the background which are not covered by the background image.

The keyword scales the background image so that the content area is
completely covered by the background image (both its width and height are equal to or
exceed the content area). As such, some parts of the background image may not be
visible in the background positioning area.

The following example illustrates the use of and :

Example

#div1
{
 
background: url(img_flower.jpg);
 
background-size: contain;  background-repeat: no-repeat;
}#div2
{
 
background: url(img_flower.jpg);
 
background-size: cover; 
background-repeat: no-repeat;
}

Define Sizes of Multiple Background Images

The property also accepts multiple values for background size
(using a comma-separated list), when working with multiple backgrounds.

The following example has three background images specified, with different
background-size value for each image:

Example

#example1 {  background: url(img_tree.gif) left top
no-repeat, url(img_flwr.gif) right bottom no-repeat, url(paper.gif) left top
repeat;  background-size: 50px, 130px, auto;}

Full Size Background Image

Now we want to have a background image on a website that covers the entire
browser window at all times.

The requirements are as follows:

  • Fill the entire page with the image (no white space)
  • Scale image as needed
  • Center image on page
  • Do not cause scrollbars

The following example shows how to do it; Use the <html> element
(the <html> element is always at least the height of the browser window). Then set a fixed and centered background on it.
Then adjust its size with the
background-size property:

Example

html {  background: url(img_man.jpg) no-repeat
center fixed;   background-size: cover;}

Hero Image

You could also use different background properties on a <div> to create a hero image (a large image with text), and place it where you want.

Example

.hero-image {  background: url(img_man.jpg) no-repeat center;  
background-size: cover;  height: 500px;  position:
relative;}

CSS background-origin Property

The CSS property specifies where the background image is
positioned.

The property takes three different values:

  • border-box — the background image starts from the upper left corner of the border
  • padding-box — (default) the background image starts from the upper left corner of the padding edge
  • content-box — the background image starts from the upper left corner of the content

The following example illustrates the property:

Example

#example1
{
  border: 10px solid black;  padding: 35px;  background: url(img_flwr.gif);
 
background-repeat: no-repeat; 
background-origin: content-box;}

CSS background-clip Property

The CSS property specifies the painting area of the background.

The property takes three different values:

  • border-box — (default) the background is painted to the outside edge of the border
  • padding-box — the background is painted to the outside edge of the padding
  • content-box — the background is painted within the content box

The following example illustrates the property:

Example

#example1
{
  border: 10px dotted black; 
padding: 35px;  background: yellow; 
background-clip: content-box;}

CSS Advanced Background Properties

Property Description
background A shorthand property for setting all the background properties in one declaration
background-clip Specifies the painting area of the background
background-image Specifies one or more background images for an element
background-origin Specifies where the background image(s) is/are positioned
background-size Specifies the size of the background image(s)

❮ Previous
Next ❯

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

CSS Advanced

CSS Rounded CornersCSS Border ImagesCSS BackgroundsCSS ColorsCSS Gradients
Linear Gradients
Radial Gradients

CSS Shadows
Shadow Effects
Box Shadow

CSS Text EffectsCSS Web FontsCSS 2D TransformsCSS 3D TransformsCSS TransitionsCSS AnimationsCSS TooltipsCSS Style ImagesCSS object-fitCSS ButtonsCSS PaginationCSS Multiple ColumnsCSS User InterfaceCSS Variables
The var() Function
Overriding Variables
Variables and JavaScript
Variables in Media Queries

CSS Box SizingCSS Media QueriesCSS MQ ExamplesCSS Flexbox
CSS Flexbox
CSS Flex Container
CSS Flex Items
CSS Flex Responsive

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

Способ 0: 100% width/height

Первый способ заключается в использовании значения 100% для одного из параметров тега img – ширины или высоты. При этом второй параметр должен быть установлен в auto для сохранения пропорций изображения. Картинка растянется до размера контейнера по одному из измерений, а второе значение будет рассчитано автоматически. В результате по краям картинки могут образоваться поля, но она поместится в отведённой области целиком, без обрезки.

<html>
  <head>
    <style>
      .wrapper {
        width: 300px;
        height: 300px;
        border: 5px solid #515151;
      }
      .exmpl {
        overflow: hidden;
        display: flex;
        justify-content: center;
        align-items: center;
      }
      .exmpl img {
        height: 100%;
        width: auto;
      }
    </style>
  </head>

  <body>
    <div class="wrapper exmpl">
      <img src="/images/braineater.png">
    </div>
  </body>
</html>

Так как при высоте 100% от высоты контейнера изображение вылезает за пределы этого контейнера по ширине, для обрезки лишнего используется свойство overflow со значением hidden. При этом, если мы хотим, чтобы в видимую область попала центральная часть изображения, его надо выровнять по центру контейнера. Проще всего это сделать задав контейнеру display: flex, и далее позиционировать изображение по вертикали и горизонтали с помощью свойств justify-content и align-items.

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

Чтобы избавиться от полей можно заменить свойства width и height на min-width и min-height (при этом ширина и высота по умолчанию примут значения auto). Тогда вне зависимости от ориентации изображения, оно заполнит область целиком.

Важно: если вы используете выравнивание с помощью flex-контейнера, добавьте flex-shrink: 0, чтобы запретить автоматическое масштабирование изображения.
 

<style>
  .wrapper {
    width: 300px;
    height: 300px;
    border: 5px solid #515151;
  }
  .exmpl {
    overflow: hidden;
    display: flex;
    justify-content: center;
    align-items: center;
  }
  .exmpl img {
    min-width: 100%;
    min-height: 100%;
    flex-shrink: 0;
  }
</style>

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

Подобным образом можно вырезать только часть изображения, увеличивая или уменьшая масштаб изображения и контролируя смещение с помощью свойства margin.

<style>
  .wrapper {
    width: 300px;
    height: 300px;
    border: 5px solid #515151;
  }
  .exmpl {
    overflow: hidden;
  }
  .exmpl img {
    width: auto;
    height: 200%;
    margin: -60px 0 0 -240px;
  }
</style>

How To Create a Hero Image

Step 1) Add HTML:

Example

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

Step 2) Add CSS:

Example

body, html {    height: 100%;}/* The hero image
*/.hero-image {  /* Use «linear-gradient» to add a darken background effect
to the image (photographer.jpg). This will make the text
easier to read */  background-image: linear-gradient(rgba(0, 0, 0, 0.5),
rgba(0, 0, 0, 0.5)), url(«photographer.jpg»);  /* Set a specific height
*/  height:
50%;  /* Position and center the image to scale
nicely on all screens */  background-position: center;  background-repeat: no-repeat;
  background-size: cover; 
position: relative;
}/* Place text in the middle of the image */
.hero-text { 
text-align: center;  position: absolute;  top: 50%;  left: 50%;  transform:
translate(-50%, -50%);  color: white;}

❮ Previous
Next ❯

Menus

Icon BarMenu IconAccordionTabsVertical TabsTab HeadersFull Page TabsHover TabsTop NavigationResponsive TopnavNavbar with IconsSearch MenuSearch BarFixed SidebarSide NavigationResponsive SidebarFullscreen NavigationOff-Canvas MenuHover Sidenav ButtonsSidebar with IconsHorizontal Scroll MenuVertical MenuBottom NavigationResponsive Bottom NavBottom Border Nav LinksRight Aligned Menu LinksCentered Menu LinkEqual Width Menu LinksFixed MenuSlide Down Bar on ScrollHide Navbar on ScrollShrink Navbar on ScrollSticky NavbarNavbar on ImageHover DropdownsClick DropdownsCascading DropdownDropdown in TopnavDropdown in SidenavResp Navbar DropdownSubnavigation MenuDropupMega MenuMobile MenuCurtain MenuCollapsed SidebarCollapsed SidepanelPaginationBreadcrumbsButton GroupVertical Button GroupSticky Social BarPill NavigationResponsive Header

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

Чтобы понять нагляднее, создайте два файла index.html и style.css.

В файле index.html элементарно пропишем путь к картинке, как мы это делали в прошлом уроке.

<!DOCTYPE html> <html>     <head>          <meta charset=»utf-8″>          <link rel= «stylesheet» type= «text/css» href= «style.css» />          <title>Изображения</title>     </head>     <body>          <img src=»images/img1.jpg»>     </body> </html>

А в файле style.css задаём размер.

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

img {width: 300px;
}

Если мы укажем высоту, то автоматически выставится ширина изображения.

img {height: 150px;
}

Ну а если мы укажем и высоту и ширину, то изображение будет иметь те размеры, которые мы указали.

img {width: 300px;height: 150px;
}

Property Values

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

Image Sprites — Hover Effect

Now we want to add a hover effect to our navigation list.

Tip: The selector can be used on all elements,
not only on links.

Our new image («img_navsprites_hover.gif») contains three navigation images
and three images to use for hover effects:

Because this is one single image, and not six separate files, there will be no
loading delay
when a user hovers over the image.

We only add three lines of code to add the hover effect:

Example

#home a:hover {  background: url(‘img_navsprites_hover.gif’) 0 -45px;}#prev a:hover {  background: url(‘img_navsprites_hover.gif’) -47px
-45px;}#next a:hover {  background: url(‘img_navsprites_hover.gif’) -91px
-45px;}

Example explained:

#home a:hover {background: url(‘img_navsprites_hover.gif’) 0 -45px;} — For all three hover images we specify the same background position, only 45px further down

❮ Previous
Next ❯

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

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

Adblock
detector