We're looking for a user researcher to understand the needs of developers and designers. Is this you or someone you know? Check out the post: https://mzl.la/2IGzdXS

Перевод не завершен. Пожалуйста, помогите перевести эту статью с английского.

 

Описание

Свойство CSS position позволяет выбрать альтернативные правила позиционирования элементов с целью упрощения использования скриптовых анимационных эффектов.

Начальное значениеstatic
Применяется квсе элементы
Наследуетсянет
Отображениевизуальный
Обработка значениякак указано
Animation typediscrete
Канонический порядокуникальный неоднозначный порядок, определённый формальной грамматикой
Создаёт контекст наложенияда

Позиционируемый элемент — это элемент, положение которого задаётся по relative, absolute, fixed, или sticky.
Относительно позиционируемый элемент — только по relative.
Абсолютно позиционируемый элемент — по absolute, или fixed.
Липко (stickily) позиционируемый элемент — по sticky.

Свойства top, right, bottom, и left устанавливают положение позиционируемых элементов.

Синтаксис

/* Keyword values */
position: static;
position: relative;
position: absolute;
position: fixed;
position: sticky;

/* Global values */
position: inherit;
position: initial;
position: unset;

Значения

static
Это значение позволяет элементу находится в обычном его состоянии, расположенным на своем месте в документе. Свойства top, right, bottom, left и z-index не применяются к данному элементу.
relative
This keyword lays out all elements as though the element were not positioned, and then adjust the element's position, without changing layout (and thus leaving a gap for the element where it would have been had it not been positioned). The effect of position:relative on table-*-group, table-row, table-column, table-cell, and table-caption elements is undefined.
absolute
Do not leave space for the element. Instead, position it at a specified position relative to its closest positioned ancestor if any, or otherwise relative to the initial containing block. Absolutely positioned boxes can have margins, and they do not collapse with any other margins.
fixed
Do not leave space for the element. Instead, position it at a specified position relative to the screen's viewport and don't move it when scrolled. When printing, position it at that fixed position on every page. This value always create a new stacking context. When an ancestor has the transform property set to something different than none then this ancestor is used as container instead of the viewport (see CSS Transforms Spec).
sticky 
The box position is calculated according to the normal flow (this is called the position in normal flow). Then the box is offset relative to its flow root and containing block and in all cases, including table elements, does not affect the position of any following boxes. When a box B is stickily positioned, the position of the following box is calculated as though B were not offset. The effect of ‘position: sticky’ on table elements is the same as for ‘position: relative’.

Formal syntax

static | relative | absolute | sticky | fixed

Examples

Relative positioning

HTML Content

<div class="box" id="one">One</div>
<div class="box" id="two">Two</div>
<div class="box" id="three">Three</div>
<div class="box" id="four">Four</div>

CSS Content

.box { 
   display: inline-block; 
   background: red; 
   width: 100px; 
   height: 100px; 
   float: left; 
   margin: 20px; 
   color: white; 
}

#two { 
   position: relative; 
   top: 20px; 
   left: 20px; 
}

Note how the other elements are displayed as if "Two" were in its normal position and taking up space.

Absolute positioning

Elements that are positioned relatively are still considered to be in the normal flow of elements in the document. In contrast, an element that is positioned absolutely is taken out of the flow and thus takes up no space when placing other elements. The absolutely positioned element is positioned relative to nearest positioned ancestor (non-static). If a positioned ancestor doesn't exist, the initial container is used.

In the example below, a positioned ancestor doesn't exist and box Three is positioned absolutely relative to the immediate ancestor (the <body> of the iframe here):

HTML Content

<div class="box" id="one">One</div>
<div class="box" id="two">Two</div>
<div class="box" id="three">Three</div>
<div class="box" id="four">Four</div>

CSS Content

.box { 
   display: inline-block; 
   background: red; 
   width: 100px; 
   height: 100px; 
   float: left; 
   margin: 20px; 
   color: white; 
}

#three { 
   position: absolute; 
   top: 20px; 
   left: 20px; 
}

Fixed positioning

Fixed positioning is similar to absolute positioning, with the exception that the element's containing block is the viewport. This is often used to create a floating element that stays in the same position even after scrolling the page. In the example below the "One" box is fixed 80px from the top of the page and 20px from the left:

HTML Content

<div class="outer">
  <p>
    Lorem ipsum dolor sit amet, consectetur adipiscing elit. Nam congue tortor eget pulvinar lobortis.
    Vestibulum ante ipsum primis in faucibus orci luctus et ultrices posuere cubilia Curae; Nam ac dolor augue.
    Pellentesque mi mi, laoreet et dolor sit amet, ultrices varius risus. Nam vitae iaculis elit.
    Aliquam mollis interdum libero. Sed sodales placerat egestas. Vestibulum ut arcu aliquam purus viverra dictum vel sit amet mi.
    Duis nisl mauris, aliquam sit amet luctus eget, dapibus in enim. Sed velit augue, pretium a sem aliquam, congue porttitor tortor.
    Sed tempor nisl a lorem consequat, id maximus erat aliquet. Sed sagittis porta libero sed condimentum.
    Aliquam finibus lectus nec ante congue rutrum. Curabitur quam quam, accumsan id ultrices ultrices, tempor et tellus.
  </p>
  <p>
    Lorem ipsum dolor sit amet, consectetur adipiscing elit. Nam congue tortor eget pulvinar lobortis.
    Vestibulum ante ipsum primis in faucibus orci luctus et ultrices posuere cubilia Curae; Nam ac dolor augue.
    Pellentesque mi mi, laoreet et dolor sit amet, ultrices varius risus. Nam vitae iaculis elit.
    Aliquam mollis interdum libero. Sed sodales placerat egestas. Vestibulum ut arcu aliquam purus viverra dictum vel sit amet mi.
    Duis nisl mauris, aliquam sit amet luctus eget, dapibus in enim. Sed velit augue, pretium a sem aliquam, congue porttitor tortor.
    Sed tempor nisl a lorem consequat, id maximus erat aliquet. Sed sagittis porta libero sed condimentum.
    Aliquam finibus lectus nec ante congue rutrum. Curabitur quam quam, accumsan id ultrices ultrices, tempor et tellus.
  </p>
  <div class="box" id="one">One</div>
</div>

CSS Content

.box {
  background: red;
  width: 100px;
  height: 100px;
  margin: 20px;
  color: white;
}
#one {
  position: fixed;
  top: 80px;
  left: 10px;
}
.outer {
  width: 500px;
  height: 300px;
  overflow: scroll;
  padding-left: 150px;
}

When viewing the top of the page, the position box appears in the upper left, and after scrolling, it remains in the same place relative to the viewport:

Sticky positioning

Sticky positioning is a hybrid of relative and fixed positioning.  The element is treated as relative positioned until it crosses a specified threshold, at which point it is treated as fixed positioned.  For instance:

#one { position: sticky; top: 10px; }

will behave just like a relatively positioned element until the viewport scrolls such that the element would be less than 10px from the top.  Then, it will be fixed to 10px from the top until the viewport is scrolled back past this threshold.

Sticky positioning is commonly used for the headings in an alphabetized listing.  The B heading will appear just below the items that begin with A until they are scrolled offscreen.  Rather than sliding offscreen with the rest of the content, the B heading will then remain fixed to the top of the viewport until all the B items have scrolled offscreen, at which point it will be covered up by the C heading.
 
You must specify a threshold with at least one of top, right, bottom, or left for sticky positioning to behave as expected.  Otherwise, it will be indistinguishable from relative positioning.
 

HTML Content

<div>
  <dl>
    <dt>A</dt>
    <dd>Andrew W.K.</dd>
    <dd>Apparat</dd>
    <dd>Arcade Fire</dd>
    <dd>At The Drive-In</dd>
    <dd>Aziz Ansari</dd>
  </dl>
  <dl>
    <dt>C</dt>
    <dd>Chromeo</dd>
    <dd>Common</dd>
    <dd>Converge</dd>
    <dd>Crystal Castles</dd>
    <dd>Cursive</dd>
  </dl>
  <dl>
    <dt>E</dt>
    <dd>Explosions In The Sky</dd>
  </dl>
  <dl>
    <dt>T</dt>
    <dd>Ted Leo & The Pharmacists</dd>
    <dd>T-Pain</dd>
    <dd>Thrice</dd>
    <dd>TV On The Radio</dd>
    <dd>Two Gallants</dd>
  </dl>
</div>

CSS Content

* {
  box-sizing: border-box;
}

dl {
  margin: 0;
  padding: 24px 0 0 0;
}

dt {
  background: #B8C1C8;
  border-bottom: 1px solid #989EA4;
  border-top: 1px solid #717D85;
  color: #FFF;
  font: bold 18px/21px Helvetica, Arial, sans-serif;
  margin: 0;
  padding: 2px 0 0 12px;
  position: -webkit-sticky;
  position: sticky;
  top: -1px;
}

dd {
  font: bold 20px/45px Helvetica, Arial, sans-serif;
  margin: 0;
  padding: 0 0 0 12px;
  white-space: nowrap;
}

dd + dd {
  border-top: 1px solid #CCC
}

 

Notes

For relatively positioned elements, the top or bottom property specifies the vertical offset from the normal position and the left or right property specifies the horizontal offset.

For absolutely positioned elements, the top, right, bottom, and left properties specify offsets from the edge of the element's containing block (what the element is positioned relative to). The margin of the element is then positioned inside these offsets.

Most of the time, absolutely positioned elements have auto values of height and width computed to fit the contents of the element. However, non-replaced absolutely positioned elements can be made to fill the available space by specifying (as other than auto) both top and bottom and leaving height unspecified (that is, auto). Likewise for left, right, and width.

Except for the case just described of absolutely positioned elements filling the available space:

  • If both top and bottom are specified (technically, not auto), top wins.
  • If both left and right are specified, left wins when direction is ltr (English, horizontal Japanese, etc.) and right wins when direction is rtl (Persian, Arabic, Hebrew, etc.).

Specifications

Specification Status Comment
CSS Level 2 (Revision 1)
Определение 'position' в этой спецификации.
Рекомендация  
CSS Positioned Layout Module Level 3
Определение 'position' в этой спецификации.
Рабочий черновик Adds sticky property value

Browser compatibility

ВозможностьChromeEdgeFirefoxInternet ExplorerOperaSafari
Базовая поддержка112114241
fixed11213741
sticky5616

32

26 — 484

Нет436.1 -webkit-
Table elements as absolute positioning containers ? ?305 ? ? ?
Table elements as sticky positioning containers Нет ?59 ? Нет ?
ВозможностьAndroid webviewChrome for AndroidEdge mobileFirefox for AndroidOpera AndroidiOS SafariSamsung Internet
Базовая поддержка Да Да Да4 Да Да Да
fixed Да Да ? ? Да ? Да
sticky565616 ?43 ?6.0
Table elements as absolute positioning containers ? ? ?305 ? ? ?
Table elements as sticky positioning containers Нет Нет ?59 Нет ? Нет

1. Before Firefox 57, absolute positioning did not work correctly when applied to elements inside tables that have border-collapse applied to them (bug 1379306).

2. In Internet Explorer, fixed positioning doesn't work if the document is in quirks mode.

3. Before Firefox 44, position: fixed didn't create a stacking context in most cases. Firefox and the specification have been modified to mimic Chrome and Safari's long-time behavior.

4. From version 26 until version 48 (exclusive): this feature is behind the layout.css.sticky.enabled preference (needs to be set to true). To change preferences in Firefox, visit about:config.

5. Firefox helps developers transition to the new behavior and detect any rendering issues it may cause on their sites by printing the following warning to the JavaScript console: "Absolute positioning of table rows and row groups is now supported. This site may need to be updated because it may depend on this feature having no effect."

Метки документа и участники

Внесли вклад в эту страницу: fscholz, Koshunch, meowow, bilazik
Обновлялась последний раз: fscholz,