Css style position attributes

position

Устанавливает способ позиционирования элемента относительно окна браузера или других объектов на веб-странице.

Краткая информация

Синтаксис

position: absolute | fixed | relative | static | sticky

Синтаксис

Описание Пример
Указывает тип значения.
A && B Значения должны выводиться в указанном порядке. &&
A | B Указывает, что надо выбрать только одно значение из предложенных (A или B). normal | small-caps
A || B Каждое значение может использоваться самостоятельно или совместно с другими в произвольном порядке. width || count
[ ] Группирует значения. [ crop || cross ]
* Повторять ноль или больше раз. [,]*
+ Повторять один или больше раз. +
? Указанный тип, слово или группа не является обязательным. inset?
Повторять не менее A, но не более B раз.
# Повторять один или больше раз через запятую. #

Значения

absolute Абсолютное позиционирование. Указывает, что элемент абсолютно позиционирован, при этом другие элементы отображаются на веб-странице словно абсолютно позиционированного элемента и нет. Положение элемента задаётся свойствами left, top, right и bottom, также на положение влияет значение свойства position родительского элемента. Так, если у родителя значение position установлено как static или родителя нет, то отсчёт координат ведётся от края окна браузера. Если у родителя значение position задано как relative , то отсчёт координат ведётся от края родительского элемента. fixed Фиксированное позиционирование. По своему действию это значение близко к absolute , но в отличие от него привязывается к указанной свойствами left , top , right и bottom точке на экране и не меняет своего положения при прокрутке веб-страницы. relative Относительное позиционирование. Положение элемента устанавливается относительно его исходного места. Добавление свойств left , top , right и bottom изменяет позицию элемента и сдвигает его в ту или иную сторону от первоначального расположения. static Статичное позиционирование. Элементы отображаются как обычно. Использование свойств left , top , right и bottom не приводит к каким-либо результатам. sticky Это сочетание относительного и фиксированного позиционирования. Элемент рассматривается как позиционированный относительно, пока он не пересекает определённый порог, после чего рассматривается как фиксированный. Обычно применяется для фиксации заголовка на одном месте, пока содержимое, к которому относится заголовок, прокручивается на странице.

Пример

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

Применение свойства position

Рис. 1. Применение свойства position

Объектная модель

Примечание

Браузер Safari поддерживает значение -webkit-sticky .

Спецификация

Каждая спецификация проходит несколько стадий одобрения.

  • Recommendation ( Рекомендация ) — спецификация одобрена W3C и рекомендована как стандарт.
  • Candidate Recommendation ( Возможная рекомендация ) — группа, отвечающая за стандарт, удовлетворена, как он соответствует своим целям, но требуется помощь сообщества разработчиков по реализации стандарта.
  • Proposed Recommendation ( Предлагаемая рекомендация ) — на этом этапе документ представлен на рассмотрение Консультативного совета W3C для окончательного утверждения.
  • Working Draft ( Рабочий проект ) — более зрелая версия черновика после обсуждения и внесения поправок для рассмотрения сообществом.
  • Editor’s draft ( Редакторский черновик ) — черновая версия стандарта после внесения правок редакторами проекта.
  • Draft ( Черновик спецификации ) — первая черновая версия стандарта.

Браузеры

static, relative, absolute 4 12 1 4 1 1
fixed 7 12 1 4 1 1
sticky 16 56 42 6.1 32
static, relative, absolute 1 1 6 1
fixed 1 1 6 1
sticky 32 6.1

Браузеры

В таблице браузеров применяются следующие обозначения.

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

Число указывает версию браузреа, начиная с которой элемент поддерживается.

См. также

Рецепты

Справочник CSS

  • !important
  • ::after
  • ::backdrop
  • ::before
  • ::first-letter
  • ::first-line
  • ::placeholder
  • ::selection
  • :active
  • :blank
  • :checked
  • :default
  • :disabled
  • :empty
  • :enabled
  • :first-child
  • :first-of-type
  • :focus
  • :focus-within
  • :fullscreen
  • :hover
  • :in-range
  • :indeterminate
  • :invalid
  • :lang
  • :last-child
  • :last-of-type
  • :link
  • :not
  • :nth-child
  • :nth-last-child
  • :nth-last-of-type
  • :nth-of-type
  • :only-child
  • :only-of-type
  • :optional
  • :out-of-range
  • :placeholder-shown
  • :read-only
  • :read-write
  • :required
  • :root
  • :target
  • :valid
  • :visited
  • @charset
  • @document
  • @font-face
  • @import
  • @keyframes
  • @media
  • @page
  • @supports
  • @viewport
  • accent-color
  • 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
  • aspect-ratio
  • backdrop-filter
  • backface-visibility
  • background
  • background-attachment
  • background-blend-mode
  • background-clip
  • background-color
  • background-image
  • background-origin
  • background-position
  • background-position-x
  • background-position-y
  • background-repeat
  • background-size
  • block-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-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
  • caption-side
  • caret-color
  • clear
  • clip
  • 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-family
  • font-kerning
  • font-size
  • font-stretch
  • font-style
  • font-variant
  • font-weight
  • height
  • hyphens
  • image-rendering
  • justify-content
  • left
  • letter-spacing
  • line-clamp
  • line-height
  • list-style
  • list-style-image
  • list-style-position
  • list-style-type
  • margin
  • margin-bottom
  • margin-left
  • margin-right
  • margin-top
  • marks
  • max-height
  • max-width
  • min-height
  • min-width
  • mix-blend-mode
  • object-fit
  • opacity
  • order
  • orphans
  • outline
  • outline-color
  • outline-offset
  • outline-style
  • outline-width
  • overflow
  • overflow-x
  • overflow-y
  • padding
  • padding-block
  • padding-block-end
  • padding-block-start
  • padding-bottom
  • padding-inline
  • padding-inline-end
  • padding-inline-start
  • padding-left
  • padding-right
  • padding-top
  • page-break-after
  • page-break-before
  • page-break-inside
  • perspective
  • perspective-origin
  • place-content
  • 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-skip-ink
  • text-decoration-style
  • text-emphasis
  • text-emphasis-color
  • text-emphasis-position
  • text-emphasis-style
  • text-fill-color
  • text-indent
  • text-orientation
  • text-overflow
  • text-shadow
  • text-stroke
  • text-stroke-color
  • text-stroke-width
  • 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
  • zoom

Источник

CSS position Property

The position property specifies the type of positioning method used for an element (static, relative, absolute, fixed, or sticky).

Default value: static
Inherited: no
Animatable: no. Read about animatable
Version: CSS2
JavaScript syntax: object.style.position=»absolute» Try it

Browser Support

The numbers in the table specify the first browser version that fully supports the property.

Note: The sticky value is not supported in Internet Explorer or Edge 15 and earlier versions.

CSS Syntax

Property Values

Value Description Demo
static Default value. Elements render in order, as they appear in the document flow Play it »
absolute The element is positioned relative to its first positioned (not static) ancestor element Play it »
fixed The element is positioned relative to the browser window Play it »
relative The element is positioned relative to its normal position, so «left:20px» adds 20 pixels to the element’s LEFT position Play it »
sticky The element is positioned based on the user’s scroll position

A sticky element toggles between relative and fixed , depending on the scroll position. It is positioned relative until a given offset position is met in the viewport — then it «sticks» in place (like position:fixed).

More Examples

Example

How to position an element relative to its normal position:

h2.pos_left <
position: relative;
left: -20px;
>

h2.pos_right position: relative;
left: 20px;
>

Example

#parent1 <
position: static;
border: 1px solid blue;
width: 300px;
height: 100px;
>

#child1 position: absolute;
border: 1px solid red;
top: 70px;
right: 15px;
>

#parent2 position: relative;
border: 1px solid blue;
width: 300px;
height: 100px;
>

#child2 position: absolute;
border: 1px solid red;
top: 70px;
right: 15px;
>

Источник

Читайте также:  Php required form fields
Оцените статью