How to resize background images with css3
Содержание:
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-image. При этом картинки ложатся друг под друга сверху вниз, начиная с первого. Каждую из них можно определить с помощью указания значений других свойств, имеющих отношение к изображению. Присваивая слою состояние прозрачности, его можно скрывать.
Таким образом, установка значений свойств фона в CSS дает возможность окрасить его в любой цвет, приняв в учет различные элементы блока (свойства и ). Вместо этого или дополнительно внутри элемента можно поместить фоновое изображение, выбрав для него определенное место, увеличив или уменьшив при этом, а также при необходимости повторив его в горизонтальном или/и вертикальном направлении (свойства , , , , , ).
Следует иметь в виду, что рассмотренные свойства не наследуют своих родителей, но цвет фона наследника ввиду его значения по умолчанию, равного , будет таким же, как и родительский. Для наследования свойства необходимо устанавливать его в значение .
Notas
Se você estiver especificando um gradient como plano de fundo e tiver especificado um junto, é melhor não especificar um tamanho que use um único componente setado como auto ou seja especificado usando apenas um valor de largura (por exemplo, ). A renderização de gradients em tais casos mudou no Firefox 8 e, no momento, geralmente é inconsistente em todos os navegadores, pois nem todos implementam a renderização em total conformidade com a especificação do CSS3 e com a .
Observe que, em particular, não é recomendável usar uma dimensão de pixel e uma dimensões com um gradient, porque é impossível replicar a renderização nas versões do Firefox antes de 8 e nos navegadores que não implementam a renderização do Firefox 8, sem saber o tamanho exato do elemento cujo plano de fundo está sendo especificado.
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 Fallbacks
Font Style
Font Size
Font Google
Font Pairings
Font Shorthand
CSS IconsCSS LinksCSS ListsCSS Tables
Table Borders
Table Size
Table Alignment
Table Style
Table Responsive
CSS DisplayCSS Max-widthCSS PositionCSS Z-indexCSS 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 SpecificityCSS !importantCSS Math Functions
Property Values
Value | Description |
---|---|
auto | Default value. The background-image contains its width and height |
length | Sets the width and height of the background image. The first value sets the width, the second value sets the height. If only one value is given, the second is set to «auto» |
percentage | Sets the width and height of the background image in percent of the parent element. The first value sets the width, the second value sets the height. If only one value is given, the second is set to «auto» |
cover | Scale the background image to be as large as possible so that the background area is completely covered by the background image. Some parts of the background image may not be in view within the background positioning area |
contain | Scale the image to the largest size such that both its width and its height can fit inside the content area |
initial | Sets this property to its default value. Read about initial |
inherit | Inherits this property from its parent element. Read about inherit |
Property Values
Value | Description | Play it |
---|---|---|
auto | Default value. The background image is displayed in its original size | Play it » |
length | Sets the width and height of the background image. The first value sets the width, the second value sets the height. If only one value is given, the second is set to «auto». Read about length units | Play it » |
percentage | Sets the width and height of the background image in percent of the parent element. The first value sets the width, the second value sets the height. If only one value is given, the second is set to «auto» | Play it » |
cover | Resize the background image to cover the entire container, even if it has to stretch the image or cut a little bit off one of the edges |
Play it » |
contain | Resize the background image to make sure the image is fully visible | Play it » |
initial | Sets this property to its default value. Read about initial | Play it » |
inherit | Inherits this property from its parent element. Read about inherit |
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 SliderFavicon
CSS Reference
CSS ReferenceCSS Browser SupportCSS SelectorsCSS FunctionsCSS Reference AuralCSS Web Safe FontsCSS Fallback FontsCSS 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
gap
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
image-rendering
@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
mask-image
mask-mode
mask-origin
mask-position
mask-repeat
mask-size
max-height
max-width
@media
min-height
min-width
mix-blend-mode
object-fit
object-position
opacity
order
orphans
outline
outline-color
outline-offset
outline-style
outline-width
overflow
overflow-wrap
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
row-gap
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
widows
width
word-break
word-spacing
word-wrap
writing-mode
z-index
CSS Advanced
CSS Rounded CornersCSS Border ImagesCSS BackgroundsCSS ColorsCSS Color KeywordsCSS Gradients
Linear Gradients
Radial Gradients
Conic Gradients
CSS Shadows
Shadow Effects
Box Shadow
CSS Text EffectsCSS Web FontsCSS 2D TransformsCSS 3D TransformsCSS TransitionsCSS AnimationsCSS TooltipsCSS Style ImagesCSS Image ReflectionCSS object-fitCSS object-positionCSS MaskingCSS 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
Possible Values
Here are the possible values:
- Specifies that the background image should be scaled, while preserving its intrinsic aspect ratio (if any), to the largest size such that both its width and its height can fit inside the background positioning area.
- Specifies that the background image should be scaled, while preserving its intrinsic aspect ratio (if any), to the smallest size such that both its width and its height can completely cover the background positioning area.
- <length>
-
Specifies the size explicitly using a lenth value. For example, will result in a background image being scaled to 300 pixels wide and 100 pixels high.
The first value provided defines the width of the background image. The second value provides the height. If only one value is given, the second becomes .
For example, provides a width of 200 pixels and a height of 50 pixels. A value of will result in the width being 200 pixels and the height being automatically determined by using the image’s intrinsic ratio and the size of the other dimension, or failing that, using the image’s intrinsic size, or failing that, treating it as 100%. In other words, the image should keep its proportions as it scales (i.e. not get distorted).
- <percentage>
-
Specifies the size explicitly using a percentage value. A percentage value is relative to the background positioning area — not to the original image size. For example, will result in a background image being scaled to 70 percent of the background positioning area.
As with the <length> values, the first value provides the width and the second provides the height. If the second value is missing, the height is automatically determined.
- Specifies that the image size is automatically determined using the intrinsic width and/or height of the image.
In addition, all CSS properties also accept the following CSS-wide keyword values as the sole component of their property value:
- Represents the value specified as the property’s initial value.
- Represents the computed value of the property on the element’s parent.
- This value acts as either or , depending on whether the property is inherited or not. In other words, it sets all properties to their parent value if they are inheritable or to their initial value if not inheritable.
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 |
conic-gradient() | Sets a conic gradient as the background image. Define at least two colors |
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-conic-gradient() | Repeats a conic gradient |
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 |
Property Values
Value | Description | Play it |
---|---|---|
auto | Default value. The background image is displayed in its original size | Play it » |
length | Sets the width and height of the background image. The first value sets the width, the second value sets the height. If only one value is given, the second is set to «auto». Read about length units | Play it » |
percentage | Sets the width and height of the background image in percent of the parent element. The first value sets the width, the second value sets the height. If only one value is given, the second is set to «auto» | Play it » |
cover | Resize the background image to cover the entire container, even if it has to stretch the image or cut a little bit off one of the edges |
Play it » |
contain | Resize the background image to make sure the image is fully visible | Play it » |
initial | Sets this property to its default value. Read about initial | Play it » |
inherit | Inherits this property from its parent element. Read about inherit |
Примеры
Пример
Укажите размер фонового изображения в процентах:
#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%;}
Пример
Укажите размер фонового изображения с помощью «cover»:
#example1 { background: url(mountain.jpg);
background-repeat: no-repeat; background-size: cover;
}
Пример
Укажите размер фонового изображения с помощью «contain»:
#example1 { background: url(mountain.jpg);
background-repeat: no-repeat; background-size:
contain;}
Пример
Здесь у нас есть два фоновых изображения. Мы указываем размер первого фонового изображения с «contain», и второе фоновое изображение с& quot;cover»:
#example1 { background: url(img_tree.gif), url(mountain.jpg);
background-repeat: no-repeat; background-size:
contain, cover;}
Property Values
Value | Description | Play it |
---|---|---|
left top left center left bottom right top right center right bottom center top center center center bottom |
If you only specify one keyword, the other value will be «center» | Play it » |
x% y% | The first value is the horizontal position and the second value is the vertical. The top left corner is 0% 0%. The right bottom corner is 100% 100%. If you only specify one value, the other value will be 50%. Default value is: 0% 0% |
Play it » |
xpos ypos | The first value is the horizontal position and the second value is the vertical. The top left corner is 0 0. Units can be pixels (0px 0px) or any other CSS units. If you only specify one value, the other value will be 50%. You can mix % and positions |
Play it » |
initial | Sets this property to its default value. Read about initial | Play it » |
inherit | Inherits this property from its parent element. Read about inherit |
Examples
The following are all valid syntaxes for the property.
/* keyword value syntax */ background-size: cover; background-size: contain; /* two-value syntax: first value specifies the width of the image and the second value specifies its height */ background-size: 50% auto; background-size: 50px 30px; background-size: 10em 12em; /* one-value syntax: the second value is always assumed to be 'auto' */ background-size: 32em; background-size: auto; background-size: 100%;
The following are all examples of background image sizes specified with the property. The image in this example is assumed to be one with intrinsic dimensions and proportions (a JPEG image, for example);
/* stretch the image to fill the background area ignoring image ratio */ background-size: 100% 100%; /* the background image is shown at its intrinsic size */ background-size: auto; /* default */ /* the background is shown with a width of 3em and its height is scaled proportionally to keep the original aspect ratio */ background-size: 3em; /* second value is assumed `auto` */ /* this one forces the background image to be 15px by 15px */ background-size: 15px 15px;
The following example stretches the image so that exactly two copies fit horizontally (notice the values of the property and the property). The aspect ratio is preserved.
background-size: 50% auto; background-repeat: repeat; background-origin: border-box;
The following example specifies the background size of two background images. The first value specifies the size of the first image, and the second value specifies the size of the second image.
background-image: url(path/to/first/image.jpg), url(path/to/second/image.png); background-size: 100% 100%, contain;
The following example will force the size of the gradient image to 100px by 100px.
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 ExponentiationJS Default ParametersGet Current URLGet Current Screen SizeGet Iframe Elements
참고
If you use a as the background and specify a to go with it, it’s best not to specify a size that uses a single component, or is specified using only a width value (for example, ). Rendering of s in such cases changed in Firefox 8, and at present is generally inconsistent across browsers, which do not all implement rendering in full accordance with and with .
Note that it’s particularly not recommended to use a pixel dimension and an dimension with a , because it’s impossible to replicate rendering in versions of Firefox prior to 8, and in browsers not implementing Firefox 8’s rendering, without knowing the exact size of the element whose background is being specified.
CSS Properties
align-contentalign-itemsalign-selfallanimationanimation-delayanimation-directionanimation-durationanimation-fill-modeanimation-iteration-countanimation-nameanimation-play-stateanimation-timing-functionbackface-visibilitybackgroundbackground-attachmentbackground-blend-modebackground-clipbackground-colorbackground-imagebackground-originbackground-positionbackground-repeatbackground-sizeborderborder-bottomborder-bottom-colorborder-bottom-left-radiusborder-bottom-right-radiusborder-bottom-styleborder-bottom-widthborder-collapseborder-colorborder-imageborder-image-outsetborder-image-repeatborder-image-sliceborder-image-sourceborder-image-widthborder-leftborder-left-colorborder-left-styleborder-left-widthborder-radiusborder-rightborder-right-colorborder-right-styleborder-right-widthborder-spacingborder-styleborder-topborder-top-colorborder-top-left-radiusborder-top-right-radiusborder-top-styleborder-top-widthborder-widthbottombox-decoration-breakbox-shadowbox-sizingbreak-afterbreak-beforebreak-insidecaption-sidecaret-color@charsetclearclipclip-pathcolorcolumn-countcolumn-fillcolumn-gapcolumn-rulecolumn-rule-colorcolumn-rule-stylecolumn-rule-widthcolumn-spancolumn-widthcolumnscontentcounter-incrementcounter-resetcursordirectiondisplayempty-cellsfilterflexflex-basisflex-directionflex-flowflex-growflex-shrinkflex-wrapfloatfont@font-facefont-familyfont-feature-settingsfont-kerningfont-sizefont-size-adjustfont-stretchfont-stylefont-variantfont-variant-capsfont-weightgapgridgrid-areagrid-auto-columnsgrid-auto-flowgrid-auto-rowsgrid-columngrid-column-endgrid-column-gapgrid-column-startgrid-gapgrid-rowgrid-row-endgrid-row-gapgrid-row-startgrid-templategrid-template-areasgrid-template-columnsgrid-template-rowshanging-punctuationheighthyphensimage-rendering@importisolationjustify-content@keyframesleftletter-spacingline-heightlist-stylelist-style-imagelist-style-positionlist-style-typemarginmargin-bottommargin-leftmargin-rightmargin-topmask-imagemask-modemask-originmask-positionmask-repeatmask-sizemax-heightmax-width@mediamin-heightmin-widthmix-blend-modeobject-fitobject-positionopacityorderorphansoutlineoutline-coloroutline-offsetoutline-styleoutline-widthoverflowoverflow-wrapoverflow-xoverflow-ypaddingpadding-bottompadding-leftpadding-rightpadding-toppage-break-afterpage-break-beforepage-break-insideperspectiveperspective-originpointer-eventspositionquotesresizerightrow-gapscroll-behaviortab-sizetable-layouttext-aligntext-align-lasttext-decorationtext-decoration-colortext-decoration-linetext-decoration-styletext-indenttext-justifytext-overflowtext-shadowtext-transformtoptransformtransform-origintransform-styletransitiontransition-delaytransition-durationtransition-propertytransition-timing-functionunicode-bidiuser-selectvertical-alignvisibilitywhite-spacewidowswidthword-breakword-spacingword-wrapwriting-modez-index