- left
- Try it
- Syntax
- Values
- Description
- Formal definition
- Formal syntax
- Examples
- Positioning elements
- HTML
- CSS
- Result
- Specifications
- Browser compatibility
- See also
- Found a content problem with this page?
- MDN
- Support
- Our communities
- Developers
- Позиционирование элементов по разным сторонам блока
- Плюсы способа
- Минусы способа
- P.S.
- Upd.
- left
- Синтаксис
- Значения
- Объектная модель
- Браузеры
- CSS свойство left
- Синтаксис
- Пример
- Пример
- Пример
- Пример
- Значения
- Поддержка браузера
left
The left CSS property participates in specifying the horizontal position of a positioned element. It has no effect on non-positioned elements.
Try it
Syntax
/* values */ left: 3px; left: 2.4em; /* s of the width of the containing block */ left: 10%; /* Keyword value */ left: auto; /* Global values */ left: inherit; left: initial; left: revert; left: revert-layer; left: unset;
Values
A negative, null, or positive that represents:
- for absolutely positioned elements, the distance to the left edge of the containing block.
- for relatively positioned elements, the distance that the element is moved to the right of its normal position.
- for absolutely positioned elements, the position of the element is based on the right property, while width: auto is treated as a width based on the content; or if right is also auto , the element is positioned where it should horizontally be positioned if it were a static element.
- for relatively positioned elements, the distance of the element from its normal position is based on the right property; or if right is also auto , the element is not moved horizontally at all.
Specifies that the value is the same as the computed value from its parent element (which might not be its containing block). This computed value is then handled as if it were a , , or the auto keyword.
Description
The effect of left depends on how the element is positioned (i.e., the value of the position property):
- When position is set to absolute or fixed , the left property specifies the distance between the element’s outer margin of left edge and the inner border of left edge of its containing block. (The containing block is the ancestor to which the element is relatively positioned.)
- When position is set to relative , the left property specifies the distance the element’s left edge is moved to the right from its normal position.
- When position is set to sticky , the left property is used to compute the sticky-constraint rectangle.
- When position is set to static , the left property has no effect.
When both left and right are defined, and width constraints don’t prevent it, the element will stretch to satisfy both. If the element cannot stretch to satisfy both, the position of the element is overspecified. When this is the case, the left value has precedence when the container is left-to-right; the right value has precedence when the container is right-to-left.
Formal definition
Initial value | auto |
---|---|
Applies to | positioned elements |
Inherited | no |
Percentages | refer to the width of the containing block |
Computed value | if specified as a length, the corresponding absolute length; if specified as a percentage, the specified value; otherwise, auto |
Animation type | a length, percentage or calc(); |
Formal syntax
Examples
Positioning elements
HTML
div id="wrap"> div id="example_1"> pre> position: absolute; left: 20px; top: 20px; pre> p> The only containing element for this div is the main window, so it positions itself in relation to it. p> div> div id="example_2"> pre> position: relative; top: 0; right: 0; pre> p>Relative position in relation to its siblings.p> div> div id="example_3"> pre> float: right; position: relative; top: 20px; left: 20px; pre> p>Relative to its sibling div above, but removed from flow of content.p> div id="example_4"> pre> position: absolute; bottom: 10px; right: 20px; pre> p>Absolute position inside of a parent with relative positionp> div> div id="example_5"> pre> position: absolute; right: 0; left: 0; top: 200px; pre> p>Absolute position with both left and right declaredp> div> div> div>
CSS
#wrap width: 700px; margin: 0 auto; background: #5c5c5c; > pre white-space: pre; white-space: pre-wrap; white-space: pre-line; word-wrap: break-word; > #example_1 width: 200px; height: 200px; position: absolute; left: 20px; top: 20px; background-color: #d8f5ff; > #example_2 width: 200px; height: 200px; position: relative; top: 0; right: 0; background-color: #c1ffdb; > #example_3 width: 600px; height: 400px; position: relative; top: 20px; left: 20px; background-color: #ffd7c2; > #example_4 width: 200px; height: 200px; position: absolute; bottom: 10px; right: 20px; background-color: #ffc7e4; > #example_5 position: absolute; right: 0; left: 0; top: 100px; background-color: #d7ffc2; >
Result
Specifications
Browser compatibility
BCD tables only load in the browser
See also
- inset , the shorthand for all related properties: top , bottom , left , and right
- The mapped logical properties: inset-block-start , inset-block-end , inset-inline-start , and inset-inline-end and the shorthands inset-block and inset-inline
- position
Found a content problem with this page?
This page was last modified on Feb 21, 2023 by MDN contributors.
Your blueprint for a better internet.
MDN
Support
Our communities
Developers
Visit Mozilla Corporation’s not-for-profit parent, the Mozilla Foundation.
Portions of this content are ©1998– 2023 by individual mozilla.org contributors. Content available under a Creative Commons license.
Позиционирование элементов по разным сторонам блока
Суть способа заключается в том, чтобы наложить блоки друг на друга посредством margin-right: -100% и содержимое правого блока выровнять по правому краю с помощью text-align: right.
Оба блока (right и left) желательно записывать в одну строку, иначе из-за символа переноса строки правый блок будет чуть-чуть вылезать за границы блока-родителя.
Ссылкам обязательно нужно ставить position: relative, иначе из-за наложения блоков некоторые могут быть некликабельные.
Плюсы способа
Главный плюс в том, что теперь для наших блоков начинает работать vertical-align. И мы легко можем выровнять их и по верхней границе и по нижней и по центру.
Минусы способа
А главный минус заключается в том, что, применяя этот способ, мы должны быть твёрдо уверены, что содержимое блоков не увеличится до такой степени, что они начнут перекрывать друг друга (к слову говоря, способ с флоутами лишён этого недостатка, так как при увеличении содержимого блоков, они будут вставать друг под друга).
P.S.
Я не встречал такого способа в интернете, посему просьба: если кто-то найдёт аналогичную статью опубликованную раньше, сообщите мне пожалуйста.
Upd.
В комментариях моё внимание внимание обратили на способ, использующий text-align: justify. Этот способ тоже хорош, но у него есть два недостатка. Во-первых он требует введения дополнительного элемента, эмулирующего последнюю строку текстового блока, а во-вторых, он не будет работать в IE6-IE7 для блочных элементов.
left
Для позиционированного элемента определяет расстояние от левого края родительского элемента, не включая отступ, поле и ширину рамки, до левого края дочернего элемента. Отсчет координат зависит от значения свойства position . Если оно равно absolute , в качестве родителя выступает окно браузера и положение элемента определяется от его левого края (рис. 1).
Рис. 1. Значение свойства left относительно окна браузера
В случае значения relative , left отсчитывается от левого края исходного положения элемента (рис. 2).
Рис. 2. Значение свойства left относительно исходного положения
Если для родительского элемента задано position : relative , то абсолютное позиционирование дочерних элементов определяет их положение от левого края родителя.
Рис. 3. Значение свойства left относительно родителя
Синтаксис
left: значение | проценты | auto | inherit
Значения
В качестве значений принимаются любые единицы длины, принятые в CSS — например, пикселы (px), дюймы (in), пункты (pt) и др. Значение свойства left может быть и отрицательным, в этом случае возможны наложения разных элементов друг на друга. При задании значения в процентах, положение элемента вычисляется в зависимости от ширины родительского элемента.
auto Не изменяет положение элемента. inherit Наследует значение родителя.
HTML5 CSS2.1 IE Cr Op Sa Fx
Результат данного примера показан на рис. 4.
Рис. 4. Применение свойства left
Объектная модель
[window.]document.getElementById(» elementID «).style.leftБраузеры
В браузере Internet Explorer 6 для абсолютно позиционированных элементов нельзя одновременно задать свойства top , left , right , bottom .
Internet Explorer до версии 7.0 включительно не поддерживает значение inherit .
CSS свойство left
Свойство left определяет положение позиционированного элемента.
Свойство left используется для установления левого края элемента и его блока для абсолютно или фиксированно позиционированных элементов. Если для свойства position задано значение «static», свойство left не будет иметь эффекта.
Эффект свойства left зависит от позиционирования элемента (смотрите свойство position).
- Если свойство position установлено на «absolute» или»fixed», left будет указывать на расстояние между левым краем элемента и левым краем его блока.
- Если свойство position установлено на «relative», left будет указывать на расстояние, которое образуется при перемещении левого края налево относительно его нормальной позиции.
- Если свойство position установлено на «sticky», свойство left изменяет свою позицию на «relative», когда элемент находится в окне просмотра, а если находится за пределами окна, значение меняется на «fixed».
- Если свойство position установлено на «static», не будет никакого эффекта.
Синтаксис
left: auto | length | initial | inherit;
Пример
html> html> head> title>Заголовок документа title> style> img < position: absolute; left: 35px; > style> head> body> h2>Пример свойства left h2> p>Установлено значение 35px. p> img src="/uploads/media/default/0001/01/0710cad7a1017902166203def268a0df2a5fd545.png" alt="CSS left property"> body> html>
Другой пример, где изображение находится внутри элемента
Пример
html> html> head> title>Заголовок документа title> style> div < height: 150px; width: 400px; background-color: #ccc; color: #666; padding: 10px; > img < position: absolute; left: 200px; > style> head> body> h2>Пример свойства left h2> div> img src="/uploads/media/default/0001/01/0710cad7a1017902166203def268a0df2a5fd545.png" alt="CSS left property"> Это некоторый элемент div, br>для которого левая сторона br>определена как 150px. div> body> html>
Пример, где свойство left указано в процентах:
Пример
html> html> head> title>Заголовок документа title> style> .example < position: absolute; left: 20%; top: 20%; width: 100px; height: 100px; background-color: #ccc; color: #666; > style> head> body> h2>Пример свойства left h2> div class="example">left: 20% div> body> html>
Пример со всеми значениями свойства:
Пример
html> html> head> title>Заголовок документа title> style> .box1 < position: absolute; left: 30px; width: 100px; height: 100px; background-color: #ccc; > .box2 < position: absolute; top: 190px; left: 50px; width: 100px; height: 100px; background-color: #444; color: #fff; > .box3 < position: absolute; left: 10%; top: 50%; width: 100px; height: 100px; background-color: #666; color: #fff; > .box4 < position: absolute; left: 20%; top: 70%; width: 100px; height: 100px; background-color: #777; color: #fff; > .box5 < position: absolute; left: -20px; top: 90%; width: 100px; height: 100px; background-color: #999; text-align: right; color: #fff; > style> head> body> h2>Пример свойства left h2> div class="box1">left: 30px div> div class="box2">left: 50px div> div class="box3">left: 10% div> div class="box4">left: 20% div> div class="box5">left: -20px div> body> html>
Значения
Значение | Описание |
---|---|
auto | Браузер устанавливает позиционирование от левого края. Значение по умолчанию. |
length | Устанавливает позиционирование от левого края в px, cm и в других единицах измерения. Отрицательные значения допустимы. |
% | Устанавливает позиционирование от левого края в процентах содержимого элемента. Отрицательные значения допустимы. |
initial | Устанавливает свойство в значение по умолчанию. |
inherit | Значение элемента наследуется от родительского элемента. |