Esta traducción está incompleta. Por favor, ayuda a traducir este artículo del inglés.
La propiedad position
de CSS especifica cómo un elemento es posicionado en el documento. Las propiedades top
, right
, bottom
, y left
determinan la ubicación final de los elementos posicionados.
El código fuente de este ejemplo interactivo se encuentra almacenado en un repositorio de GitHub. Si quisiera contribuir al proyecto de ejemplos interactivos, por favor clone https://github.com/mdn/interactive-examples y envíenos sus contribuciones como un pull request.
Tipos de posicionamiento
- Un elemento posicionado es un elemento cuyo valor computado de
position
esrelative
,absolute
,fixed
, osticky
. (En otras palabras, cualquiera exceptostatic
). - Un elemento posicionado relativamente es un elemento cuyo valor computado de
position
esrelative
. Las propiedadestop
ybottom
especifican el desplazamiento vertical desde su posición original; las propiedadesleft
yright
especifican su desplazamiento horizontal. - Un elemento posicionado absolutamente es un elemento cuyo valor computado de
position
esabsolute
ofixed
. Las propiedadestop
,right
,bottom
, yleft
especifican 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 posicionado fijamente es un elemento cuyo valor de
position
computado essticky
. Es tratado como un elemento posicionado relativamente hasta que su bloque contenedor cruza un límite establecido (como por ejemplo dando atop
cualquier valor distinto de auto), dentro de su flujo principal (o el contenedor dentro del cual se mueve), punto al cual es tratado como "fijo" hasta que alcance el borde opuesto de su bloque contenedor.
La mayoría de las veces, los elementos absolutamente posicionados que tienen su height
y width
establecidos en auto
son ajustados hasta acomodarse a su contenido. Sin embargo, elementos non-replaced y absolutamente posicionados se pueden crear para llenar el espacio vertical disponible, especificando tanto top
como bottom
, y dejando height
sin especificar (es decir, auto
). De igual manera se pueden utilizar para llenar el espacio horizontal disponible especificando tanto left
como right
, y dando a width
el valor de auto
.
A excepción del caso anteriormente descrito (de elementos posicionados absolutamente rellenando el espacio disponible):
- Si ambos,
top
ybottom
están especificados (técnicamente, noauto
),top
gana. - Si ambos,
left
yright
, están especificados,left
gana cuando esltr
(Inglés, japonés horizontal, etc.) yright
gana cuandodirection
esrtl
(Persa, árabe, hebreo, etc.).
Sintaxis
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
, andz-index
no tienen efecto. Este es el valor por defecto. relative
- El elemento es posicionado de acuerdo al flujo normal del documento, y luego es desplazado con relación a sí mismo, con base en los valores de
top
,right
,bottom
, andleft
. El desplazamiento no afecta la posición de ningún otro elemento; por lo que, el espacio que se le da al elemento en el esquema de la página es el mismo como si la posición fuerastatic
. Este valor crea un nuevo contexto de apilamiento, donde el valor dez-index
no esauto
. El efecto que tienerelative
sobre los elementostable-*-group
,table-row
,table-column
,table-cell
, ytable-caption
no está definido. absolute
- El elemento es removido del flujo normal del documento, sin crearse espacio alguno para el elemento en el esquema de la página. Es posicionado relativo a su ancestro posicionado más cercano, si lo hay; de lo contrario, se ubica relativo al bloque contenedor inicial. Su posición final está determinada por los valores de
top
,right
,bottom
, yleft
. - Este valor crea un nuevo contexto de apilamiento cuando el valor de
z-index
no esauto
. Elementos absolutamente posicionados pueden tener margen, y no colapsan con ningún otro margen. fixed
- El elemento es removido del flujo normal del documento, sin crearse espacio alguno para el elemento en el esquema de la página. Es posicionado con relación al bloque contenedor inicial establecido por el viewport, except when one of its ancestors has a
transform
,perspective
, orfilter
property set to something other thannone
(see the CSS Transforms Spec), in which case that ancestor behaves as the containing block. (Note that there are browser inconsistencies withperspective
andfilter
contributing to containing block formation.) Its final position is determined by the values oftop
,right
,bottom
, andleft
. - This value always creates a new stacking context. 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
, andleft
. 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 withoverflow: hidden
orauto
. (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.
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 & 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 inicial | static |
---|---|
Applies to | all elements |
Heredable | no |
Media | visual |
Valor calculado | como se especifica |
Animation type | discrete |
Canonical order | el orden único no-ambigüo definido por la gramática formal |
Creates stacking context | yes |
Compatibilidad
Desktop | Mobile | ||||||||||||
---|---|---|---|---|---|---|---|---|---|---|---|---|---|
Soporte básico | Chrome Soporte completo 1 | Edge Soporte completo 12 | Firefox
Soporte completo
1
| IE
Soporte completo
4
| Opera Soporte completo 4 | Safari Soporte completo 1 | WebView Android Soporte completo Si | Chrome Android Soporte completo Si | Edge Mobile Soporte completo Si | Firefox Android Soporte completo 4 | Opera Android Soporte completo Si | Safari iOS Soporte completo Si | Samsung Internet Android Soporte completo Si |
fixed | Chrome Soporte completo 1 | Edge Soporte completo 12 | Firefox
Soporte completo
1
| IE Soporte completo 7 | Opera Soporte completo 4 | Safari Soporte completo 1 | WebView Android Soporte completo Si | Chrome Android Soporte completo Si | Edge Mobile ? | Firefox Android ? | Opera Android Soporte completo Si | Safari iOS ? | Samsung Internet Android Soporte completo Si |
sticky | Chrome Soporte completo 56 | Edge Soporte completo 16 | Firefox
Soporte completo
32
| IE Sin soporte No | Opera Soporte completo 43 | Safari
Soporte completo
6.1
| WebView Android Soporte completo 56 | Chrome Android Soporte completo 56 | Edge Mobile Sin soporte No | Firefox Android ? | Opera Android Soporte completo 43 | Safari iOS ? | Samsung Internet Android Soporte completo 6.0 |
Table elements as absolute positioning containers | Chrome ? | Edge ? | Firefox
Soporte completo
30
| IE ? | Opera ? | Safari ? | WebView Android ? | Chrome Android ? | Edge Mobile ? | Firefox Android
Soporte completo
30
| Opera Android ? | Safari iOS ? | Samsung Internet Android ? |
Table elements as sticky positioning containers | Chrome Sin soporte No | Edge ? | Firefox Soporte completo 59 | IE ? | Opera Sin soporte No | Safari ? | WebView Android Sin soporte No | Chrome Android Sin soporte No | Edge Mobile ? | Firefox Android Soporte completo 59 | Opera Android Sin soporte No | Safari iOS ? | Samsung Internet Android Sin soporte No |
Leyenda
- Soporte completo
- Soporte completo
- Sin soporte
- Sin soporte
- Compatibility unknown
- Compatibility unknown
- Ver notas de implementación.
- Ver notas de implementación.
- El usuario debe de habilitar explícitamente esta característica.
- El usuario debe de habilitar explícitamente esta característica.
- Requiere de un prefijo de proveedor o un de nombre diferente para su uso.
- Requiere de un prefijo de proveedor o un de nombre diferente para su uso.