Esta traducción está incompleta. Por favor, ayuda a traducir este artículo del inglés.

La propiedad position de CSS especifica como se posicionara este en el documento. las propiedades top, right, bottom, y left determinan la localizacion final de los elementos posicionados.

Tipos de posicionamiento

  • Un elemento posicionado es un elemento cuyo valor de position computado es relative, absolute, fixed, o sticky. (En otras palabras, cualquiera excepto static.)
  • Un elemento posicionado relativamente es un elemento cuyo valor de position computado es relative. Las propiedades top y bottom especifican el desplazamiento vertical desde su posición original; las propiedades left y rightespecifican su desplazamiento horizontal
  • Un elemento posicionado absolutamente es un elemento cuyo valor de  position computado es absolute o fixed. Las propiedades top, right, bottom, y  left especifica el desplazamiento desde los bordes del bloque contenedor del elemento. (El bloque contenedor es el ancestro más cercano posicionado.) Si el elemento tiene márgenes, se agregarán al desplazamiento.
  • Un elemento positionado como stickily es un elemento cuyo valor de  position computado es sticky. se trata como un elemento posicionado relativamente hasta que su bloque contenedor cruza el límite establecido, desde ese punto queda fijo.

La mayor parte del tiempo, los elementos absolutamente posicionados tienen su height y width son automáticos y se ajustarán a su contenido. Sin embargo, non-replaced, los elementos absolutamente posicionados se pueden hacer para llenar el espacio vertical disponible especificando ambos top y bottom y dejando height sin especificar (esto es, auto). De igual manera se puede utilizar para llenar el espacio horizontal disponible especificando ambos: left y right y dejando widthen auto.

Excepto para el caso que se acaba de describir (de elementos posicionados absolutamente rellenando el espacio disponible):

  • Si ambos, top y bottom están especificados (técnicamente, no auto), top gana.
  • Si ambos, left y right, están especificados,  left gana cuando es ltr (Inglés, japonés horizontal, etc.) y right gana cuando direction es rtl (Persa, árabe, hebreo, etc.).

Syntax

La propiedad position es especificada como una palabra única elegida de la siguiente lista de valores.

Valores

static
El elemento es posicionado de acuerdo al flujo normal del documento. Las propiedades top, right, bottom, left, and z-index no tienen efecto. Este es el valor por defecto.
relative
The element is positioned according to the normal flow of the document, and then offset relative to itself based on the values of top, right, bottom, and left. The offset does not affect the position of any other elements; thus, the space given for the element in the page layout is the same as if position were static. This value creates a new stacking context when the value of z-index is not auto. The effect of relative on table-*-group, table-row, table-column, table-cell, and table-caption elements is undefined.
absolute
The element is removed from the normal document flow; no space is created for the element in the page layout. Instead, it is positioned relative to its closest positioned ancestor if any; otherwise, it is placed relative to the initial containing block. Its final position is determined by the values of top, right, bottom, and left. This value creates a new stacking context when the value of z-index is not auto. Absolutely positioned boxes can have margins, and they do not collapse with any other margins.
fixed
The element is removed from the normal document flow; no space is created for the element in the page layout. Instead, it is positioned relative to the screen's viewport and doesn't move when scrolled. Its final position is determined by the values of top, right, bottom, and left. This value always creates a new stacking context. When an ancestor has the transform, perspective, or filter property set to something other than none, that ancestor is used as the container instead of the viewport (see CSS Transforms Spec). In printed documents, the element is placed in the same position on every page.
sticky
The element is positioned according to the normal flow of the document, and then offset relative to its flow root and containing block, including table-related elements, based on the values of top, right, bottom, and left. The offset does not affect the position of any other elements. This value always creates a new stacking context. Note that sticky, by specification, will not work inside element with overflow: hidden or auto. (ref: Github issue on W3C CSSWG)

Formal syntax

static | relative | absolute | sticky | fixed

Examples

Relative positioning

Relatively positioned elements are offset a given amount from their normal position within the document, but without the offset affecting other elements. In the example below, note how the other elements are placed as if "Two" were taking up the space of its normal location.

HTML

<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

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

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

Absolute positioning

Elements that are relatively positioned remain in the normal flow of the document. In contrast, an element that is absolutely positioned is taken out of the flow; thus, other elements are positioned as if it did not exist. The absolutely positioned element is positioned relative to its nearest positioned ancestor (i.e., the nearest ancestor that is not static). If a positioned ancestor doesn't exist, the initial container is used. In the example below, box "Two" has no positioned ancestor, so it is positioned relative to the the <body> of the document.

HTML

<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

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

#two {
  position: absolute;
  top: 20px;
  left: 20px;
  background: blue;
}

Fixed positioning

Fixed positioning is similar to absolute positioning, with the exception that the element's containing block is the viewport. This can be used to create a floating element that stays in the same position regardless of scrolling. In the example below, box "One" is fixed at 80 pixels from the top of the page and 10 pixels from the left. Even after scrolling, it remains in the same place relative to the viewport.

HTML

<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

.box {
  width: 100px;
  height: 100px;
  background: red;
  color: white;
}

#one {
  position: fixed;
  top: 80px;
  left: 10px;
  background: blue;
}

.outer {
  width: 500px;
  height: 300px;
  overflow: scroll;
  padding-left: 150px;
}

Sticky positioning

Sticky positioning can be thought of as a hybrid of relative and fixed positioning. A stickily positioned element is treated as relatively positioned until it crosses a specified threshold, at which point it is treated as fixed until it reaches the boundary of its parent. For instance...

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

...would position the element with id one relatively until the viewport were scrolled such that the element would be less than 10 pixels from the top. Beyond that threshold, the element would be fixed to 10 pixels from the top.

A common use for sticky positioning is for the headings in an alphabetized list. 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, and so on.
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

<dl>
  <div>
    <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>
  </div>
  <div>
    <dt>C</dt>
    <dd>Chromeo</dd>
    <dd>Common</dd>
    <dd>Converge</dd>
    <dd>Crystal Castles</dd>
    <dd>Cursive</dd>
  </div>
  <div>
    <dt>E</dt>
    <dd>Explosions In The Sky</dd>
  </div>
  <div>
    <dt>T</dt>
    <dd>Ted Leo &amp; The Pharmacists</dd>
    <dd>T-Pain</dd>
    <dd>Thrice</dd>
    <dd>TV On The Radio</dd>
    <dd>Two Gallants</dd>
  </div>
</dl>

CSS

* {
  box-sizing: border-box;
}

dl > div {
  background: #FFF;
  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;
}

Specifications

Specification Status Comment
CSS Level 2 (Revision 1)
La definición de 'position' en esta especificación.
Recommendation  
CSS Positioned Layout Module Level 3
La definición de 'position' en esta especificación.
Working Draft Adds sticky property value.

Valor inicialstatic
Applies toall elements
Heredableno
Mediavisual
Valor calculadocomo se especifica
Animation typediscrete
Canonical orderel orden único no-ambigüo definido por la gramática formal
Creates stacking contextyes

Browser compatibility

FeatureChromeEdgeFirefoxInternet ExplorerOperaSafari
Soporte básico112114241
fixed11213741
sticky5616

32

26 — 484

No436.1 -webkit-
Table elements as absolute positioning containers ? ?305 ? ? ?
Table elements as sticky positioning containers No ?59 ? No ?
FeatureAndroid webviewChrome para AndroidEdge mobileFirefox para AndroidOpera AndroidiOS SafariSamsung Internet
Soporte básico Si Si Si4 Si Si Si
fixed Si Si ? ? Si ? Si
sticky565616 ?43 ?6.0
Table elements as absolute positioning containers ? ? ?305 ? ? ?
Table elements as sticky positioning containers No No ?59 No ? No

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."

Etiquetas y colaboradores del documento

Etiquetas: 
Última actualización por: OttoChamo,