How to set background color in html?

Другие примеры

Пример

Укажите цвет фона с шестнадцатеричным значением:

body {background-color: #92a8d1;}

Пример

Укажите цвет фона с RGB-значением:

body {background-color: rgb(201, 76, 76);}

Пример

Укажите цвет фона с RGBA значением:

body {background-color: rgba(201, 76, 76, 0.3);}

Пример

Укажите цвет фона с HSL значением:

body {background-color: hsl(89, 43%, 51%);}

Пример

Укажите цвет фона с HSLA значением:

body {background-color: hsla(89, 43%, 51%, 0.3);}

Пример

Задать цвета фона для различных элементов:

body {    background-color: #fefbd8;}h1 {   
background-color: #80ced6;}div {    background-color: #d5f4e6;
}span {   
background-color: #f18973;}

Добавление фонового изображения

Следующие правила добавляют цвет фона и фоновое изображение к элементу <body>. Затем мы задаем для элемента <div> (с классом wrapper) белый цвет фона:

body {
  background-color: #333;
  background-image: url('image.png');
}
.wrapper {
  width: 80%;
  margin: 20px auto 40px auto;
  background-color: #fff;
  color: #333;
}

Попробовать »

Свойство background-color просто добавляет цвет фона на страницу или к определенному элементу. Мы использовали в примере background-color, чтобы установить фоновый цвет для элемента <body> и внутри элемента <div>. Если бы цвет фона для элемента <div> не был бы установлен, то в качестве фона был бы показан фон, который установлен для <body>, так как по умолчанию все элементы имеют прозрачный фон.

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

Если возникает вопрос зачем устанавливать цвет фона, когда используется фоновое изображение, то на него можно легко ответить: если по каким-либо причинам фоновое изображение не может быть загружено на страницу, в этом случае будет отображаться цвет фона.

HSL Colors

HSL stands for Hue, Saturation and Lightness.

An HSL color value is specified with: hsl(hue, saturation, lightness).

  1. Hue is a degree on the color wheel (from 0 to 360):
    • 0 (or 360) is red
    • 120 is green
    • 240 is blue
  2. Saturation is a percentage value: 100% is the full color.
  3. Lightness is also a percentage; 0% is dark (black) and 100% is white.

hsl(0, 100%, 30%);
hsl(0, 100%, 50%);
hsl(0, 100%, 70%);
hsl(0, 100%, 90%);

The following example defines different HSL colors:

Example

#p1 {background-color: hsl(120, 100%, 50%);}  /* green */#p2 {background-color: hsl(120, 100%, 75%);}  /* light green */#p3 {background-color: hsl(120, 100%, 25%);}  /* dark
green */#p4 {background-color: hsl(120, 60%, 70%);}   /* pastel green */

Прозрачность и прозрачность цвета фона HTML

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

Допустим, у вас есть две кнопки Bootstrap рядом. Вы хотите, чтобы посетители нажимали одну кнопку – например, кнопку отправки – и не нажимали другую – вариант «нет, спасибо». Вот HTML:

Вы можете уменьшить непрозрачность последнего, чтобы он казался деактивированным и приводил к меньшему количеству кликов. В этом случае вы можете использовать свойство CSS opacity. Значения этого свойства варьируются от 0 до 1, где 0 означает полную прозрачность, а 1 – совсем непрозрачность (или полную непрозрачность).

Чтобы сделать вторую кнопку прозрачной на 40%, вы должны использовать селектор класса .btn-secondary, чтобы применить уникальные свойства стиля ко второй кнопке, а не к обеим кнопкам. Затем вы должны установить уровень непрозрачности на 0,4.

Вот CSS:

Вот результат:

Возможно, вы заметили, что нам не нужно использовать свойство CSS background-color, потому что мы использовали классы модификаторов Bootstrap по умолчанию.

Узнайте больше о Bootstrap в The Ultimate Guide to Bootstrap CSS.

Property Values

Value Description CSS
background-color Specifies the background color to be used 1
background-image Specifies ONE or MORE background images to be used 1
background-position Specifies the position of the background images 1
background-size Specifies the size of the background images 3
background-repeat Specifies how to repeat the background images 1
background-origin Specifies the positioning area of the background images 3
background-clip Specifies the painting area of the background images 3
background-attachment Specifies whether the background images are fixed or scrolls with the rest of the page 1
initial Sets this property to its default value. Read about initial 3
inherit Inherits this property from its parent element. Read about inherit 2

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-punctuationheighthyphens@importisolationjustify-content@keyframesleftletter-spacingline-heightlist-stylelist-style-imagelist-style-positionlist-style-typemarginmargin-bottommargin-leftmargin-rightmargin-topmax-heightmax-width@mediamin-heightmin-widthmix-blend-modeobject-fitobject-positionopacityorderoutlineoutline-coloroutline-offsetoutline-styleoutline-widthoverflowoverflow-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-spacewidthword-breakword-spacingword-wrapwriting-modez-index

Описание

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

Допускается указывать значения следующих свойств: background-clip, background-color, background-image, background-origin, background-position, background-repeat, background-size и background-attachment.

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

Если в свойстве задаётся размер изображения (background-size), то он должен указываться после указания начальной позиции изображения, через символ / (слэш):

background: background-position/background-size;

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

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

Значение по умолчанию: смотрите отдельно каждое свойство, входящее в состав краткого метода
Применяется: ко всем элементам, а также к псевдо-элементам ::first-letter и ::first-line
Анимируется: да, смотрите каждое свойство, входящее в состав краткого метода, отдельно
Наследуется: нет
Версия: CSS1, CSS3
Синтаксис JavaScript: object.style.background=»red url(smiley.gif) top left no-repeat»

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 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 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 !important

Opacity

The CSS property sets the opacity for
the whole element (both background color and text will be opaque/transparent).

The property value must be a number between 0.0 (fully transparent) and 1.0 (fully opaque).

rgb(255, 0, 0);opacity:0.2;
rgb(255, 0, 0);opacity:0.4;
rgb(255, 0, 0);opacity:0.6;
rgb(255, 0, 0);opacity:0.8;

Notice that the text above will also be
transparent/opaque!

The following example shows different elements with opacity:

Example

#p1 {background-color:rgb(255,0,0);opacity:0.6;}  /* red with opacity
*/#p2 {background-color:rgb(0,255,0);opacity:0.6;}  /* green with
opacity */#p3 {background-color:rgb(0,0,255);opacity:0.6;}  /* blue
with opacity */

❮ Previous
Next ❯

More Examples

Example

Specify the background color with a HEX value:

body {background-color: #92a8d1;}

Example

Specify the background color with an RGB value:

body {background-color: rgb(201, 76, 76);}

Example

Specify the background color with an RGBA value:

body {background-color: rgba(201, 76, 76, 0.3);}

Example

Specify the background color with a HSL value:

body {background-color: hsl(89, 43%, 51%);}

Example

Specify the background color with a HSLA value:

body {background-color: hsla(89, 43%, 51%, 0.3);}

Example

Set background colors for different elements:

body {  background-color: #fefbd8;}h1 {  background-color: #80ced6;}div {  background-color: #d5f4e6;
}span {  background-color: #f18973;}

How to Change the Background Image in CSS

What if you want the background to be an image rather than a solid color or gradient? The shorthand background property is a familiar friend.

Make sure the image is in the same folder as your HTML and CSS files. Otherwise you’ll have to use the file path inside the parentheses rather than just the name:

Whoah! Looks like the image is way too zoomed in. You can fix that with the background-size property.

To use the shorthand background property in conjunction with the background-size property cover, you must also specify background-position properties and separate the values with a backslash (even if they’re default positional values such as top left.)

There you go! A properly sized background image in one line of CSS.

Note: Be wary of including large background images that take up a lot of storage space. These can be tough to load on mobile, where you have all of two seconds to give users a reason to stay on the page.

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

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
@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
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
width
word-break
word-spacing
word-wrap
writing-mode

z-index

Прозрачность

CSS позволяет легко изменять уровни прозрачности элементов. Для этого мы будем использовать свойство opacity и модель RGBa.

Свойство opacity или как сделать фон страницы в html прозрачным

Свойство opacity используется для указания уровня непрозрачности (который является обратным для прозрачности).

  • При значении 1 элемент будет полностью непрозрачным: это поведение по умолчанию.
  • При значении 0 элемент будет полностью прозрачным.

Вам нужно выбрать значение от до 1. При значении 0,6 элемент будет на 60% непрозрачным, и вы сможете видеть сквозь него!

Вот как это можно использовать:

p
{
opacity: 0.6;
}

Вот пример, который даст представление о прозрачности.

body
{
background: url('snow.png');
}
p
{
background-color: black;
color: white;
opacity: 0.3;
}

Прозрачный абзац

Прозрачность работает во всех браузерах, включая Internet Explorer, начиная с версии IE9 и выше.

Если вы примените свойство opacity к элементу веб-страницы, все содержимое этого элемента станет прозрачным. Если хотите сделать цвет фона прозрачным, лучше всего использовать указание RGBa.

Модель RGBa

CSS3 предоставляет еще один способ изменения прозрачности: модель RGBa. Это RGB, которое мы рассматривали ранее, но с четвертым параметром: уровнем прозрачности (альфа-каналом). При значении 1 фон полностью непрозрачен. При значении менее 1 он становится прозрачным.

p
{
background-color: rgba(255, 0, 0, 0.5); /* Красный, полупрозрачный фон */
}

Это обозначение распознают все современные браузеры, включая Internet Explorer (начиная с версии IE9 и выше). Для устаревших браузеров рекомендуется указывать стандартный код RGB, в дополнение к RGBa.

p
{
background-color: rgb(255,0,0); /* Для старых браузеров */
background-color: rgba(255,0,0,0.5); /* Для новых браузеров */
}

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-punctuationheighthyphens@importisolationjustify-content@keyframesleftletter-spacingline-heightlist-stylelist-style-imagelist-style-positionlist-style-typemarginmargin-bottommargin-leftmargin-rightmargin-topmax-heightmax-width@mediamin-heightmin-widthmix-blend-modeobject-fitobject-positionopacityorderoutlineoutline-coloroutline-offsetoutline-styleoutline-widthoverflowoverflow-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-spacewidthword-breakword-spacingword-wrapwriting-modez-index

Примеры

Пример

Укажите цвет фона с значением HEX:

body {background-color: #92a8d1;}

Пример

Укажите цвет фона со значением RGB:

body {background-color: rgb(201, 76, 76);}

Пример

Укажите цвет фона со значением RGBA:

body {background-color: rgba(201, 76, 76, 0.3);}

Пример

Укажите цвет фона со значением HSL:

body {background-color: hsl(89, 43%, 51%);}

Пример

Укажите цвет фона со значением HSLA:

body {background-color: hsla(89, 43%, 51%, 0.3);}

Пример

Установите цвета фона для различных элементов:

body {    background-color: #fefbd8;}h1 {   
background-color: #80ced6;}div {    background-color: #d5f4e6;
}span {   
background-color: #f18973;}

HSLA Colors

HSLA color values are an extension of HSL color values with an alpha channel — which specifies the opacity
for a color.

An HSLA color value is specified with: hsla(hue, saturation, lightness, alpha), where the
alpha parameter defines the opacity. The alpha parameter is a number between 0.0 (fully transparent) and 1.0 (fully opaque).

hsla(0, 100%, 30%, 0.3);
hsla(0, 100%, 50%, 0.3);
hsla(0, 100%, 70%, 0.3);
hsla(0, 100%, 90%, 0.3);

The following example defines different HSLA colors:

Example

#p1 {background-color: hsla(120, 100%, 50%, 0.3);}  /* green with opacity */#p2 {background-color: hsla(120, 100%, 75%, 0.3);}  /* light green with opacity */#p3 {background-color: hsla(120, 100%, 25%, 0.3);}  /* dark
green with opacity */#p4 {background-color: hsla(120, 60%, 70%, 0.3);}   /* pastel green
with opacity */

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 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 !important

Как изменить цвет фона в HTML

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

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

Если бы это был единственный CSS, то у всего на странице был бы такой же голубой фон, как показано ниже.

Но если мы хотим изменить цвет фона таблицы, вы можете использовать встроенный CSS для нацеливания на этот единственный элемент. Вот HTML со встроенным CSS:

Вот результат:

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

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

Adblock
detector