Полностью адаптивный фон с использованием css

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

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

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

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

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 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 ❯

Положение фона

Для управления положением фонового рисунка на странице применяется стилевое свойство background-position, оно одновременно устанавливает координаты изображения по горизонтали и вертикали. Чтобы отменить повторение фоновой картинки используется значение no-repeat. Также можно воспользоваться универсальным background, как показано в примере 4.

Пример 4. Положение фона

<!DOCTYPE html>
<html>
<head>
<meta charset=»utf-8″>
<title>Положение фонового рисунка</title>
<style>
body {
background: url(/example/image/tomato.jpg) right bottom no-repeat fixed; /* Параметры фона */
margin-right: 200px; /* Отступ справа */
}
</style>
</head>
<body>
<h1>Консервы из помидор</h1>
<p>Плоды отбирают с хорошей ровной окраской, плотные и однородные по
размеру, укладывают в банки и заливают кипящим рассолом (на 1 л воды — 35 г
поваренной соли и 6 г лимонной кислоты). Банки прикрывают крышками и
ставят на прогревание, выдерживая в кипящей воде: литровые — 5-8,
трехлитровые — 12-15 мин. Затем их укупоривают и охлаждают.</p>
<p>Примерный расход сырья и продуктов на литровую банку: помидоров
красных отборных — 550-600 г, соли — 15 г, лимонной кислоты — 3 г.</p>
</body>
</html>

Результат данного примера показан на рис. 5. Изображение позиционируется в нужном месте с помощью значений right bottom свойства background. Чтобы текст не отображался поверх рисунка, справа на странице добавлен отступ через margin-right.

Рис. 5. Фоновая картинка в правом нижнем углу окна

Точное положение фона задаётся с помощью пикселей, но в основном применяется процентная запись или ключевые слова, как показано ниже:

  • top left = left top = 0% 0% (в левом верхнем углу);
  • top = top center = center top = 50% 0% (по центру вверху);
  • right top = top right = 100% 0% (в правом верхнем углу);
  • left = left center = center left = 0% 50% (по левому краю и по центру);
  • center = center center = 50% 50% (по центру);
  • right = right center = center right = 100% 50% (по правому краю и по центру);
  • bottom left = left bottom = 0% 100% (в левом нижнем углу);
  • bottom = bottom center = center bottom = 50% 100% (по центру внизу);
  • bottom right = right bottom = 100% 100% (в правом нижнем углу).

Таким образом, для добавления фона в правый нижний угол для background-position можно указать значение right bottom или bottom right или 100% 100%. Они равнозначны и дают одинаковый результат.

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

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 изменить размер картинки.

background-size

Не зависимо от оригинала картинки, размер можно менять от меньшего до большего. В CSS для изменения размера картинки поможет свойство background-size.
В свойстве background-size могут применяться абсолютные единицы измерения, такие как px, em, cm и др..

background-size: ширина высота;

По умолчанию ширина и высота установлена как auto, что оставляет исходные размеры изображения.

Например, вы загрузили на сайт картинку размерами 200×200 px, но вам по каким-то причинам нужно ее увеличить до размера 500×200 px . Вот так будут выглядеть параметры background-siz.

background-size: 500px 200px;

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

можно так:

background-size: 200px;

а можно вот так:

background-size: 200px auto;

Пример:

<html>
<head>
<style>
body
{
 background:url(картинка.jpg);
 background-size:500px 200px;
 background-repeat:no-repeat;
}
</style>
</head>
<body>
<p>текст сайта</p>
</body>
</html>

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

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

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

По умолчанию, фоновое изображение позиционируется в верхнем левом углу элемента, используя 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 Пример позиционирования фонового изображения.

How To Create a Full Height Image

Use a container element and add a background image to the container with .
Tip: Use 50% to create a half page background image. Then use the following background properties to center and scale the image perfectly:

Note: To make sure that the image covers the whole screen, you must also
apply to both <html> and <body>:

body, html {  height: 100%;}.bg {  
/* The image used */  background-image: url(«img_girl.jpg»);  /* Full height */ 
height: 100%;   /* Center and scale the image nicely */ 
background-position: center;  background-repeat:
no-repeat;  background-size: cover;}

Half page background image:

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

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

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 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-weightgridgrid-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-eventspositionquotesresizerightscroll-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

Обтекание (выравнивание) картинки текстом.

float

Как сделать в CSS так, чтобы на странице изображение обтекало текстом? Выравнивание картинки в CSS аналог HTML-выравнивания картинки <IMG align=”right” …>, вот только в CSS по какой стороне будет выравнивание элементов определяет float.

float: left | right | none;

 Значение:

left — выровнять картинку по левому краю, текст обтекает его по правой стороне.

right — выровнять картинку по правому краю, текст обтекает по левой стороне.

none — выравнивание и обтекание не задается (значение по умолчанию).

Пример

<html>
 <head>
 <title>Обтекание</title>
 <style>
 .leftimg {
 float:left; /* Выравнивание по левому краю */
 margin: 5px 5px 5px 0; /* Отступы вокруг картинки */
 }
 .rightimg {
 float: right; /* Выравнивание по правому краю */
 margin: 5px 0 5px 5px; /* Отступы вокруг картинки */
 }
 </style>
 </head>
 <body>
 <h2>Основы CSS</h2>
 <p><img src="images/1.jpg" class="leftimg">
 Приветствую всех читателей и случайных посетителей моего блога.
 Сегодня я бы хотел вам рассказать о незаменимом инструменте веб-дизайнера - CSS.
 CSS (Cascading Style Sheets) – это каскадные таблицы стилей, которые хранят в
 себе правила для группы или одиночного элемента. CSS используют для изменения
внешнего вида дизайна сайта (цвет, размер текста, фон и др.).</p>
 <h2>Основы CSS</h2>
 <p><img src="images/2.jpg" class="rightimg">
 Давайте перейдем к основам CSS.CSS файл имеет расширение *.css.
 Часто веб-мастера присваивают CSS файлу имя style (style.css).
 CSS файл тесно связан с HTML. Другими словами, это можно объяснить
 так: CSS без HTML работать не будет.
 Предлагаю для общего понимания рассмотреть пример, как можно объединить
 HTML с CSS файлом.</p>
 </body>
</html>

Здесь я указал отступы текста от картинки

margin: 5px 0 5px 5px;

Результат:

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

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

Adblock
detector