float

float

Иногда при вёрстке блока нужно, чтобы текст рядом с картинкой занимал всё оставшееся место, а после картинки располагался на всю ширину блока. Для таких ситуаций и создан float . Элемент, для которого указано это свойство, частично выходит из потока: все элементы блочного контекста, прописанные в коде после элемента с float , занимают его место, а элементы строчного контекста — «обтекают» его.

Как пишется

Скопировать ссылку «Как пишется» Скопировано

 .element  float: left;> .element  float: left; >      

В файле стилей пишем селектор элемента, который будем «обтекать», и указываем одно из трёх значений свойства:

  • left — элемент встанет у левого края родительского блока.
  • right — элемент встанет у правого края родительского блока.
  • none — значение по умолчанию, элемент останется в потоке.

Если мы задаём какому-то элементу свойство float и пишем к нему, скажем, абзац текста, а ниже добавляем ещё один абзац, который по задумке должен быть независимым, то второй абзац всё ещё может «обтекать» элемент с float . Поэтому нам нужно прекратить влияние этого свойства, чтобы вернуться к обычному потоку документа. Для этого можно использовать так называемый «clearfix». После элемента, на котором мы хотим прекратить обтекание, можно вставить пустой элемент, обычно с классом clearfix , и прописать свойство clear :

 .clearfix  clear: both;> .clearfix  clear: both; >      

Также можно не вставлять отдельный элемент в разметку, а обойтись псевдоэлементом : : after — этот вариант предпочтительнее.

Несколько лет назад для похожей цели появилось значение flow — root для свойства display — оно как бы изолирует обтекание. Достаточно применить его к блоку, внутри которого есть элемент с float — и влияние float не будет распространяться вне этого блока. А относительно соседей он будет вести себя как обычный блочный элемент со статичным позиционированием.

Также для подобной изоляции можно указать блоку свойство overflow : hidden . Отличие состоит в том, что flow — root позволяет использовать свойство overflow : visible .

Подсказки

Скопировать ссылку «Подсказки» Скопировано

💡 Применяя float к элементу, мы неявно делаем его блочным.

На практике

Скопировать ссылку «На практике» Скопировано

Лена Райан советует

Скопировать ссылку «Лена Райан советует» Скопировано

🛠 float не предназначен для создания сеток или табличной раскладки! Раньше не было другого способа разбить контент на колонки и поставить их рядом друг с другом. Но сейчас для этого есть флексы и гриды, а float используется только для «обтекания».

Источник

float

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

Синтаксис

float: left | right | none | inherit

Значения

left Выравнивает элемент по левому краю, а все остальные элементы, вроде текста, обтекают его по правой стороне. right Выравнивает элемент по правому краю, а все остальные элементы обтекают его по левой стороне. none Обтекание элемента не задается. inherit Наследует значение родителя.

HTML5 CSS 2.1 IE 9 Cr 15 Op 11 Sa 5 Fx 8

        
Duis autem dolor in hendrerit in vulputate velit esse molestie consequat, vel illum dolore eu feugiat nulla facilisis at vero eros et accumsan et iusto odio dignissim qui blandit praesent luptatum zzril delenit au gue duis dolore te feugat nulla facilisi.

Результат данного примера показан на рис. 1.

Применение свойства float

Рис. 1. Применение свойства float

Объектная модель

[window.]document.getElementById(» elementID «).style.styleFloat [window.]document.getElementById(» elementID «).style.cssFloat

Браузеры

В браузере Internet Explorer 6 наблюдается ошибка с удвоением значения левого или правого отступа для плавающих элементов, вложенных в родительские элементы. Удваивается тот отступ, который прилегает к стороне родителя. Проблема обычно решается добавлением display: inline для плавающего элемента. Также в этом браузере добавляется отступ 3px (так называемый «трехпиксельный баг») в направлении, заданном значением float .

Internet Explorer до версии 7.0 включительно не поддерживает значение inherit .

Источник

CSS Layout — float and clear

The CSS float property specifies how an element should float.

The CSS clear property specifies what elements can float beside the cleared element and on which side.

The float Property

The float property is used for positioning and formatting content e.g. let an image float left to the text in a container.

The float property can have one of the following values:

  • left — The element floats to the left of its container
  • right — The element floats to the right of its container
  • none — The element does not float (will be displayed just where it occurs in the text). This is default
  • inherit — The element inherits the float value of its parent

In its simplest use, the float property can be used to wrap text around images.

Example — float: right;

The following example specifies that an image should float to the right in a text:

Pineapple

Lorem ipsum dolor sit amet, consectetur adipiscing elit. Phasellus imperdiet, nulla et dictum interdum, nisi lorem egestas odio, vitae scelerisque enim ligula venenatis dolor. Maecenas nisl est, ultrices nec congue eget, auctor vitae massa. Fusce luctus vestibulum augue ut aliquet. Mauris ante ligula, facilisis sed ornare eu, lobortis in odio. Praesent convallis urna a lacus interdum ut hendrerit risus congue. Nunc sagittis dictum nisi, sed ullamcorper ipsum dignissim ac.

Example

Example — float: left;

The following example specifies that an image should float to the left in a text:

Pineapple

Lorem ipsum dolor sit amet, consectetur adipiscing elit. Phasellus imperdiet, nulla et dictum interdum, nisi lorem egestas odio, vitae scelerisque enim ligula venenatis dolor. Maecenas nisl est, ultrices nec congue eget, auctor vitae massa. Fusce luctus vestibulum augue ut aliquet. Mauris ante ligula, facilisis sed ornare eu, lobortis in odio. Praesent convallis urna a lacus interdum ut hendrerit risus congue. Nunc sagittis dictum nisi, sed ullamcorper ipsum dignissim ac.

Example

Example — No float

In the following example the image will be displayed just where it occurs in the text (float: none;):

Pineapple

Lorem ipsum dolor sit amet, consectetur adipiscing elit. Phasellus imperdiet, nulla et dictum interdum, nisi lorem egestas odio, vitae scelerisque enim ligula venenatis dolor. Maecenas nisl est, ultrices nec congue eget, auctor vitae massa. Fusce luctus vestibulum augue ut aliquet. Mauris ante ligula, facilisis sed ornare eu, lobortis in odio. Praesent convallis urna a lacus interdum ut hendrerit risus congue. Nunc sagittis dictum nisi, sed ullamcorper ipsum dignissim ac.

Example

Example — Float Next To Each Other

Normally div elements will be displayed on top of each other. However, if we use float: left we can let elements float next to each other:

Example

Источник

float

The float CSS property places an element on the left or right side of its container, allowing text and inline elements to wrap around it. The element is removed from the normal flow of the page, though still remaining a part of the flow (in contrast to absolute positioning).

Try it

A floating element is one where the computed value of float is not none .

As float implies the use of the block layout, it modifies the computed value of the display values, in some cases:

Specified value Computed value
inline block
inline-block block
inline-table table
table-row block
table-row-group block
table-column block
table-column-group block
table-cell block
table-caption block
table-header-group block
table-footer-group block
inline-flex flex
inline-grid grid
other unchanged

Note: If you’re referring to this property from JavaScript as a member of the HTMLElement.style object, modern browsers support float , but in older browsers you have to spell it as cssFloat . This was an exception to the rule, that the name of the DOM member is the camel-case name of the dash-separated CSS name (because «float» is a reserved word in JavaScript, as seen in the need to escape «class» as «className» and escape ‘s «for» as «htmlFor»).

Syntax

/* Keyword values */ float: left; float: right; float: none; float: inline-start; float: inline-end; /* Global values */ float: inherit; float: initial; float: revert; float: revert-layer; float: unset; 

The float property is specified as a single keyword, chosen from the list of values below.

Values

The element must float on the left side of its containing block.

The element must float on the right side of its containing block.

The element must not float.

The element must float on the start side of its containing block. That is the left side with ltr scripts, and the right side with rtl scripts.

The element must float on the end side of its containing block. That is the right side with ltr scripts, and the left side with rtl scripts.

Formal definition

Initial value none
Applies to all elements, but has no effect if the value of display is none .
Inherited no
Computed value as specified
Animation type discrete

Formal syntax

float =
block-start |
block-end |
inline-start |
inline-end |
snap-block |
|
snap-inline |
|
left |
right |
top |
bottom |
none |
footnote

=
snap-block( , [ start | end | near ]? )

=
snap-inline( , [ left | right | near ]? )

Examples

How floated elements are positioned

As mentioned above, when an element is floated, it is taken out of the normal flow of the document (though still remaining part of it). It is shifted to the left, or right, until it touches the edge of its containing box, or another floated element.

In this example, there are three colored squares. Two are floated left, and one is floated right. Note that the second «left» square is placed to the right of the first. Additional squares would continue to stack to the right, until they filled the containing box, after which they would wrap to the next line.

A floated element is at least as tall as its tallest nested floated children. We gave the parent width: 100% and floated it to ensure it is tall enough to encompass its floated children, and to make sure it takes up the width of the parent so we don’t have to clear its adjacent sibling.

HTML

section> div class="left">1div> div class="left">2div> div class="right">3div> p> Lorem ipsum dolor sit amet, consectetur adipiscing elit. Morbi tristique sapien ac erat tincidunt, sit amet dignissim lectus vulputate. Donec id iaculis velit. Aliquam vel malesuada erat. Praesent non magna ac massa aliquet tincidunt vel in massa. Phasellus feugiat est vel leo finibus congue. p> section> 

CSS

section  box-sizing: border-box; border: 1px solid blue; width: 100%; float: left; > div  margin: 5px; width: 50px; height: 150px; > .left  float: left; background: pink; > .right  float: right; background: cyan; > 

Result

Clearing floats

Sometimes you may want to force an item to move below any floated elements. For instance, you may want paragraphs to remain adjacent to floats, but force headings to be on their own line. See clear for examples.

Specifications

Browser compatibility

BCD tables only load in the browser

See also

Found a content problem with this page?

This page was last modified on Feb 23, 2023 by MDN contributors.

Your blueprint for a better internet.

Источник

Читайте также:  Python for index range
Оцените статью