CSS-макет — свойство позиции


Оглавление

    Показать оглавление


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


Позиция Недвижимость

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

Существует пять различных значений позиции:

static
relative
fixed
absolute
sticky

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


Свойство CSS позиция: статическая;

HTML-элементы по умолчанию располагаются статически.

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

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

This <div> element has position: static;

Вот используемый CSS:

Пример

div.static {
  position: static;
  border: 3px solid #73AD21;
}

Попробуйте сами →

<!DOCTYPE html>
<html>
<head>
<style>
div.static {
  position: static;
  border: 3px solid #73AD21;
}
</style>
</head>
<body>

<h2>position: static;</h2>

<p>An element with position: static; is not positioned in any special way; it is always positioned according to the normal flow of the page:</p>

<div class="static">
This div element has position: static;
</div>

</body>
</html>



Свойство CSS позиция: относительная;

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

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

This <div> element has position: relative;

Вот используемый CSS:

Пример

div.relative {
  position: relative;
  
left: 30px;
  border: 3px solid #73AD21;
}

Попробуйте сами →

<!DOCTYPE html>
<html>
<head>
<style>
div.relative {
  position: relative;
  left: 30px;
  border: 3px solid #73AD21;
}
</style>
</head>
<body>

<h2>position: relative;</h2>

<p>An element with position: relative; is positioned relative to its normal position:</p>

<div class="relative">
This div element has position: relative;
</div>

</body>
</html>




Свойство CSS позиция: фиксированная;

Элемент с position: fix; позиционируется относительно области просмотра, что означает, что он всегда остается на том же месте, даже если страницу прокручивают. Вершина, Свойства right, Bottom и Left используются для позиционирования элемента.

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

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

Пример

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

Попробуйте сами →

<!DOCTYPE html>
<html>
<head>
<style>
div.fixed {
  position: fixed;
  bottom: 0;
  right: 0;
  width: 300px;
  border: 3px solid #73AD21;
}
</style>
</head>
<body>

<h2>position: fixed;</h2>

<p>An element with position: fixed; is positioned relative to the viewport, which means it always stays in the same place even if the page is scrolled:</p>

<div class="fixed">
This div element has position: fixed;
</div>

</body>
</html>


This <div> element has position: fixed;

Свойство CSS позиция: абсолютная;

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

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

Примечание. Элементы с абсолютным позиционированием удаляются из обычного потока и могут перекрывать элементы.

Вот простой пример:

This <div> element has position: relative;
This <div> element has 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;
}

Попробуйте сами →

<!DOCTYPE html>
<html>
<head>
<style>
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;
}
</style>
</head>
<body>

<h2>position: absolute;</h2>

<p>An element with position: absolute; is positioned relative to the nearest positioned ancestor (instead of positioned relative to the viewport, like fixed):</p>

<div class="relative">This div element has position: relative;
  <div class="absolute">This div element has position: absolute;</div>
</div>

</body>
</html>



Свойство CSS position: Sticky;

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

Прикрепленный элемент переключается между относительным и фиксированным в зависимости от положения прокрутки. Он позиционируется относительно до тех пор, пока в окне просмотра не будет достигнута заданная позиция смещения - тогда он «прилипает» на месте (например, позиция: фиксированная).

Примечание. Internet Explorer не поддерживает фиксированное позиционирование. Safari требует -webkit- префикс (см. пример ниже). Вы также должны указать хотя бы один из top, right, внизу или слева для липкое позиционирование для работы.

В этом примере липкий элемент прикрепляется к верхней части страницы (top: 0), когда вы достигаете его положения прокрутки.

Пример

div.sticky {
  position: -webkit-sticky; /* Safari */
  position: 
  sticky;
  top: 0;
  background-color: green;
  
  border: 2px solid #4CAF50;
}

Попробуйте сами →

<!DOCTYPE html>
<html>
<head>
<style>
div.sticky {
  position: -webkit-sticky;
  position: sticky;
  top: 0;
  padding: 5px;
  background-color: #cae8ca;
  border: 2px solid #4CAF50;
}
</style>
</head>
<body>

<p>Try to <b>scroll</b> inside this frame to understand how sticky positioning works.</p>

<div class="sticky">I am sticky!</div>

<div style="padding-bottom:2000px">
  <p>In this example, the sticky element sticks to the top of the page (top: 0), when you reach its scroll position.</p>
  <p>Scroll back up to remove the stickyness.</p>
  <p>Some text to enable scrolling.. Lorem ipsum dolor sit amet, illum definitiones no quo, maluisset concludaturque et eum, altera fabulas ut quo. Atqui causae gloriatur ius te, id agam omnis evertitur eum. Affert laboramus repudiandae nec et. Inciderint efficiantur his ad. Eum no molestiae voluptatibus.</p>
  <p>Some text to enable scrolling.. Lorem ipsum dolor sit amet, illum definitiones no quo, maluisset concludaturque et eum, altera fabulas ut quo. Atqui causae gloriatur ius te, id agam omnis evertitur eum. Affert laboramus repudiandae nec et. Inciderint efficiantur his ad. Eum no molestiae voluptatibus.</p>
</div>

</body>
</html>



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

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

Пример

Cinque Terre
Bottom Left
Top Left
Top Right
Bottom Right
Centered

Попробуй сам:

Вверху слева →

<!DOCTYPE html>
<html>
<head>
<style>
.container {
  position: relative;
}

.topleft {
  position: absolute;
  top: 8px;
  left: 16px;
  font-size: 18px;
}

img { 
  width: 100%;
  height: auto;
  opacity: 0.3;
}
</style>
</head>
<body>

<h2>Image Text</h2>
<p>Add some text to an image in the top left corner:</p>

<div class="container">
  <img src="img_5terre_wide.jpg" alt="Cinque Terre" width="1000" height="300">
  <div class="topleft">Top Left</div>
</div>

</body>
</html>


Вверху справа →

<!DOCTYPE html>
<html>
<head>
<style>
.container {
  position: relative;
}

.topright {
  position: absolute;
  top: 8px;
  right: 16px;
  font-size: 18px;
}

img { 
  width: 100%;
  height: auto;
  opacity: 0.3;
}
</style>
</head>
<body>

<h2>Image Text</h2>
<p>Add some text to an image in the top right corner:</p>

<div class="container">
  <img src="img_5terre_wide.jpg" alt="Cinque Terre" width="1000" height="300">
  <div class="topright">Top Right</div>
</div>

</body>
</html>


Внизу слева →

<!DOCTYPE html>
<html>
<head>
<style>
.container {
  position: relative;
}

.bottomleft {
  position: absolute;
  bottom: 8px;
  left: 16px;
  font-size: 18px;
}

img { 
  width: 100%;
  height: auto;
  opacity: 0.3;
}
</style>
</head>
<body>

<h2>Image Text</h2>
<p>Add some text to an image in the bottom left corner:</p>

<div class="container">
  <img src="img_5terre_wide.jpg" alt="Cinque Terre" width="1000" height="300">
  <div class="bottomleft">Bottom Left</div>
</div>

</body>
</html>


Внизу справа →

<!DOCTYPE html>
<html>
<head>
<style>
.container {
  position: relative;
}

.bottomright {
  position: absolute;
  bottom: 8px;
  right: 16px;
  font-size: 18px;
}

img { 
  width: 100%;
  height: auto;
  opacity: 0.3;
}
</style>
</head>
<body>

<h2>Image Text</h2>
<p>Add some text to an image in the bottom right corner:</p>

<div class="container">
  <img src="img_5terre_wide.jpg" alt="Cinque Terre" width="1000" height="300">
  <div class="bottomright">Bottom Right</div>
</div>

</body>
</html>


По центру →

<!DOCTYPE html>
<html>
<head>
<style>
.container {
  position: relative;
}

.center {
  position: absolute;
  top: 50%;
  width: 100%;
  text-align: center;
  font-size: 18px;
}

img { 
  width: 100%;
  height: auto;
  opacity: 0.3;
}
</style>
</head>
<body>

<h2>Image Text</h2>

<p>Center text in image:</p>

<div class="container">
  <img src="img_5terre_wide.jpg" alt="Cinque Terre" width="1000" height="300">
  <div class="center">Centered</div>
</div>

</body>
</html>



Больше примеров

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

Задайте форму элемента

<!DOCTYPE html>
<html>
<head>
<style>
img {
  position: absolute;
  clip: rect(0px,60px,200px,0px);
}
</style>
</head>
<body>

<img src="w3css.gif" width="100" height="140">

</body>
</html>




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

bottom

Устанавливает нижний край поля для позиционированного блока.

clip

Вырезает абсолютно позиционированный элемент

left

Устанавливает левый край поля для позиционированного блока.

position

Указывает тип позиционирования элемента.

right

Устанавливает правый край поля для позиционированного блока.

top

Устанавливает верхний край поля для позиционированного блока.