Position в css – Position (absolute, relative и fixed) — способы позиционирования Html элементов в CSS (правила left, right, top и bottom)

position — Уеб технология за разработчици

Свойството position (положение) в CSS  служи за задаване на различни правила за разполагане на елементи. То е създадено да се ползва за програмно осъществени анимационни ефекти.

/* Ключови думи за стойностите */
position: static;
position: relative;
position: absolute;
position: fixed;
position: sticky;

/* Глобални стойности */
position: inherit;
position: initial;
position: unset;
  • Разположен (positioned) елемент е този, чиято изчислена стойност  на свойството position е някоя от следните: relativeabsolutefixed или sticky.
  • Относително разположен елемент е този, чиято изчислена стойност на положението му е  relative (относително).
  •  Безусловно разположен (absolutely positioned) елемент е този, чиято изчислена стойност на разположението му е
    absolute
    (безусловно) или fixed (застопорена).
  • Лепкаво разположен (stickily positioned) е този, чиято изчислена стойност на свойството position e sticky.

Свойствата top, right, bottom и left указват разположението на елементите.

Правопис

Стойността на свойството position  се задава като отделна ключова дума. Възможните стойности са в списъка долу.

Стойности

static
Тази стойност задава подразбиращото се поведение на елемента. Това означава, че елементът е разположен на естественото си място, където се намира в документа. Свойствата top, right, bottom, left и z-index не важат и не се прилагат.
relative
This keyword lays out all elements as though the element were not positioned, and then adjusts the element’s position
relative to itself
, 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 creates a new stacking context. When an ancestor has the transform property set to something different from 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 related elements is the same as for ‘position: relative’.

Formal syntax

static | relative | absolute | sticky | fixed

Примери

Относително разполагане

HTML съдържание
<div>One</div>
<div>Two</div>
<div>Three</div>
<div>Four</div>
CSS съдържание
.box { 
   display: inline-block; 
   background: red; 
   width: 100px; 
   height: 100px; 
   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.

Безусловно разползагане

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 съдържание
<div>One</div>
<div>Two</div>
<div>Three</div>
<div>Four</div>
CSS съдържание
.box { 
   display: inline-block; 
   background: red; 
   width: 100px; 
   height: 100px; 
   color: white; 
}

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

Застопорено разполагане

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 съдържание
<div>
  <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>One</div>
</div>
CSS съдържание
.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 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 съдържание
<!-- Learn about this code on MDN: https://developer.mozilla.org/en-US/docs/Web/CSS/position -->


<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 {
  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
}

 

Бележки

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

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

Съвместимост на уебчетците

FeatureChromeEdgeFirefox (Gecko)Internet ExplorerOperaSafari (WebKit)
Basic support1(Yes)1.0 (1.0) [1]4.0 [3]4.01.0 (85)
fixed value1(Yes)1.0 (1.0) [4]7.04.01.0 (85)
sticky value56?32 (32.0) [2]No support [5](Yes)6.1 -webkit-
FeatureAndroid WebviewChrome for AndroidEdgeFirefox Mobile (Gecko)IE PhoneOpera MobileSafari Mobile
Basic support11(Yes)1.0 (1.0) [1]?(Yes)7.0 -webkit-

[1] Since Firefox 30, Gecko allows <tr>, <thead>, and  <tfoot> elements with a position: relative; style to act as absolute positioning containers. This means that a position: absolute; styled element inside the table can be positioned relative to these elements. In other browsers and in older versions of Firefox, setting position: relative; on a table row or row group has no effect. Firefox helps developers transition to the new behavior and detect any rendering issues it may cause on their sites by printing a warning to the JavaScript console if you use this feature: Relative 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.

[2] Sticky positioning only worked in Firefox 26 to Firefox 31, included, when the about:config preference layout.css.sticky.enabled is set to true. From Firefox 27 to 31, it was the default value for Nightly and Aurora versions of the browser. The preference has been removed in Firefox 48.

[3] In Internet Explorer, fixed positioning doesn’t work if the document is in quirks mode.

[4] Prior to Firefox 44, position: fixed didn’t created a stacking context in most cases. The specification, and Gecko implementation, have been modified to mimick Chrome and Safari long time behavior.

[5] Sticky positioning is in development for Edge

Position в CSS

«Position в CSS» – шестой урок учебника CSS. В этом уроке речь пойдет об использовании методов CSS позиционирования.

CSS позиционирование является мощнейшим инструментом форматирования информации, расположенной на странице. Position в CSS позволяет:

  • расположить элемент в любом месте на странице
  • расположить элемент в любом месте относительно другого элемента
  • расположить несколько элементов друг за другом и определить им приоритет отображения
  • определить правила отображения текста при переполнении какого–либо элемента

Position в CSS — основные параметры.

Position – позволяет определить способ позиционирования элемента:

  • static – позиционирование не применяется. Элемент статичен.
  • relative – позиционирование будет производиться относительно нормального положения элемента на странице.
  • absolute – позиционирование элемента будет производиться в абсолютных величинах. Начало оси координат располагается в левом верхнем углу. Ось x направленна вправо, ось y – вниз.
  • fixed – задает жесткую позицию элемента. То есть при прокрутке страницы элемент будет прокручиваться тоже, сохраняя свою позицию, относительно окна браузера.

Bottom – задает положение нижнего края элемента:

  • auto – браузер выставляет нижнюю позицию самостоятельно
  • % – позиция задается в процентном отношении от нижнего края окна
  • length – нижняя позиция задается в пикселах, также допускаются отрицательные значения

Left – задает положение левого края элемента:

  • auto – браузер выставляет левую позицию самостоятельно
  • % – позиция задается в процентном отношении от левого края окна
  • length – левая позиция задается в пикселах, также допускаются отрицательные значения

Right – задает положение правого края элемента:

  • auto – браузер выставляет правую позицию самостоятельно
  • % – позиция задается в процентном отношении от правого края окна
  • length – правая позиция задается в пикселах, также допускаются отрицательные значения

Top – задает положение верхнего края элемента:

  • auto – браузер выставляет верхнюю позицию самостоятельно
  • % – позиция задается в процентном отношении от верхнего края окна
  • length – верхняя позиция задается в пикселях, также допускаются отрицательные значения

Примеры позиционирования элементов:

.p1 {
top : – 15%; left : 40%;
position : relative;}
.p2 {
position : static;
top : 35%; left: 35%;}
.p3 {
left:90%; top:40%; position : fixed;
}
.p4 {
left: – 80px; top: 200px; position : absolute;
}

Дополнительные параметры позиционирования:

Vertical – align – позволяет задать выравнивание элемента по вертикали:

  • baseline – элемент выравнивается по родительскому элементу.
  • sub – элемент выравнивается, как нижний индекс.
  • super – элемент выравнивается, как верхний индекс.
  • top – элемент выравнивается по уровню самого высокого элемента в строке
  • text – top – вершина элемента выравнивается по вершине шрифта родительского элемента.
  • middle – элемент выравнивается по середине.
  • bottom – элемент выравнивается по уровню самого низкого элемента.
  • text – bottom – нижняя часть элемента выравнивается по размеру самой маленькой буквы текста.
  • % – выравнивает элемент в % от значения параметра «line – height«. Допускаются отрицательные значения.

Overflow – задает инструкции, выполняемые в случае переполнения элементом допустимой области родительского элемента:

  • visible – содержимое будет выводиться даже в случае переполнения
  • hidden – содержимое будет обрезано по границе допустимого заполнения
  • scroll – содержимое будет обрезано по границе допустимого заполнения, но браузер создаст полосу прокрутки для просмотра содержимого целиком
  • auto – ситуация будет определена браузером

z – index – задает уровень приоритета элемента, что позволяет располагать одни элементы позади других.

Значения z – index могут быть отрицательными.


Position в CSS — действительно многофункциональный и замечательный элемент разметки. Используя позиционирование можно создавать замечательный графический дизайн для сайта, подгоняя элементы друг к другу с хирургической точностью. Но спешу вас предупредить, не размещайте элементы за пределами видимости страницы, тем более если это ссылки. Такая манипуляция может вызвать жестокие санкции, ведь данный метод относится к черным методам оптимизации.

В следующем уроке мы поговорим об очень интересном CSS инструменте — псевдо-классах.

СSS Позиция



Свойство position определяет тип метода позиционирования и используется для элемента, имеет значения (static, relative, fixed или absolute).


Свойство позиция

Свойство position указывает тип метода позиционирования, используется для элемента.

Есть четыре различных значения позиции:

  • static статическая позиция
  • relative относительная позиция
  • fixed фиксированная позиция
  • absolute абсолютная позиция

Затем элементы устанавливаются с помощью свойств top, right, bottom и left. Однако, это свойство не будет работать, если свойство position установлено одно. position также работает по-разному, в зависимости от значения позиции.


Позиция статистическая

Элемент HTML position: static; расположены статический по умолчанию.

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

Элемент с position: static; не позиционируется по-особенному; он всегда располагается в соответствии с нормальным потоком страницы:

Элемент <div> имеет position: static;

Пример CSS, который используется:


Позиция относительная

Элемент с position: relative; позиционируется относительно своего нормального положения.

Установка свойств top, right, bottom и left относительно позиционируемого элемента приведет к регулировке от своего нормального положения. Контент не будет установлен с любой стороны, элемента.

Элемент <div> имеет position: relative;

Пример CSS, который используется:


Позиция фиксированная

Элемент с position: fixed; позиционируется относительно окна просмотра, что означает, что он всегда остается в том же месте, даже если страница прокручивается. Свойства top, right, bottom и left используются для установки элемента.

Фиксированный элемент не оставляет зазор на странице, где он обычно находится.

Обратите внимание на фиксированный элемент в нижнем правом углу страницы. Пример CSS, который используется:

Пример

div.fixed {
   position: fixed;
   bottom: 0;
   right: 0;
   width: 300px;
   border: 3px solid #73AD21;
}

Редактор кода »

Элемент <div> имеет position: fixed;


Позиция абсолютная

Элемент с position: absolute; позиционируется абсолютно ближайшего позиционированного предка (позиционируется абсолютно окна просмотра, вместо фиксированного).

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

Примечание: Элемент «расположенный» один, положение которого ничего не значит, кроме static.

Элемент имент position: relative;

Элемент <div> имент position: absolute;

Пример CSS, который используется:

Пример

div.relative {
   position: relative;
   width: 400px;
   height: 200px;
   border: 3px solid #73AD21;
}

div.absolute {
   position: absolute;
   top: 80px;
   right: 0;
   width: 200px;
   height: 100px;
   border: 3px solid #73AD21;
}

Редактор кода »

Перекрывающий элемент

Когда элементы расположены в окне просмотра дисплея, они могут перекрывать друг друга.

Свойство z-index определяет порядок элемента в стеке (какой элемент должен быть помещен в передней части или за элементом)

Элемент может иметь положительное или отрицательное расположение стеки:

Так как изображение имеет z-index:1, оно будет помещено за текстом.

Элемент с большим порядком стека всегда находится перед элементом, с более низким порядком стека за элементом.

Примечание: Если два элемента расположенны без перекрытия z-index, указанный элемент расположенный последним в коде HTML отображается вверху.


Расположение текста в изображении

Как разместить текст поверх изображения:


Еще примеры

Установить форму элемента
Этот пример показывает, как установить форму элемента. Элемент закрепляется в форму и отображается.


Проверьте себя с помощью упражнений!


Все CSS свойства позиции

СвойстваОписание
positionУстанавливает тип позиции для элемента
bottomУстанавливает бокс по нижниму краю поля
leftУстанавливает бокс по левому краю поля
rightУстанавливает бокс по правому краю поля
topУстанавливает бокс по верхнему краю поля
clipПодрезка абсолютной позиции элемента
z-indexУстанавливает порядок элемента в стеке «перед» или «за»

Урок 11. Позиционирование в CSS


В CSS есть свойства, которые отвечают за позиционирование элемента. То есть, ему отступы будут заданы от края документа или относительно родительского элемента? Для этого используется свойство position. Оно имеет несколько значений, о них и напишу.

absolute


Данное значение устанавливается для таких элементов, которые должны отображаться так, как будто других на странице и не существует.
Положение зависит от того, есть ли родительские элементы с таким же свойством (position absolute relative fixed):
1. если нет, то положение будет определяться относительно левого верхнего угла окна
2. если есть, то будет положение будет определяться относительно них

fixed


Чёткое фиксированное положение элемента. Его координаты будут привязаны к X,Y сторонам браузера. При скролле страницы элементы будут оставаться на своём месте.

relative


Данное значение определяет положение элемента уже относительно его исходного места.

static


Значение устанавливает элемент так, как он должен располагаться в обычном состояние относительно других элементов.

Располагаем элементы


Установив значения absolute relative fixed элементом возможно манипулировать, перемещая его относительно других элементов. Делается это свойствами top, right, bottom, left. Значения данных свойств устанавливают на сколько сместится элемент относительного текущего положения.
#wrapper {
  position: relative;
  bottom: 15px; /* смещен на 15px от низа */
  left: 30px; /* смещен на 30px слева */
}

При этом можно указывать и отрицательные значения.
#wale {
  position: relative;
  right: -10px; /* смещен на -10px справа (10px слева) */
}

Примеры позиционирования в CSS

<!DOCTYPE html>
<html>
 <head>
  <meta charset="utf-8">
  <title>position</title>
  <style>
   .layer1 {
    position: relative; /* Относительное позиционирование */
    background: #f0f0f0; /* Цвет фона */
    height: 200px; /* Высота блока */
   }
   .layer2 {
    position: absolute; /* Абсолютное позиционирование */
    bottom: 15px; /* Положение от нижнего края */
    right: 15px; /* Положение от правого края */
    line-height: 1px;
   }
  </style>
 </head>
 <body>
  <div class="layer1">
   <div class="layer2">
     <div style="width:250px;height:100px;background-color:#50A5D6"></div>
   </div>
  </div>
 </body>
</html>

Ну и уже по обыкновению смотрим пример проработки) Для наглядности попробуйте изменить размеры окна браузера.Демонстрация Скачать исходники

С помощью данного свойства можно выстраивать сложную структуру web-документа. Главное не запутаться)

Спасибо за внимание!

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

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