Сдвигаем картинку

clear

The clear CSS property sets whether an element must be moved below (cleared) floating elements that precede it. The clear property applies to floating and non-floating elements.

Try it

When applied to non-floating blocks, it moves the border edge of the element down until it is below the margin edge of all relevant floats. The non-floated block’s top margin collapses.

Vertical margins between two floated elements on the other hand will not collapse. When applied to floating elements, the margin edge of the bottom element is moved below the margin edge of all relevant floats. This affects the position of later floats, since later floats cannot be positioned higher than earlier ones.

The floats that are relevant to be cleared are the earlier floats within the same block formatting context.

Note: If an element contains only floated elements, its height collapses to nothing. If you want it to always be able to resize, so that it contains floating elements inside it, set the value of the element’s display property to flow-root .

#container  display: flow-root; > 

Syntax

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

Values

Is a keyword indicating that the element is not moved down to clear past floating elements.

Is a keyword indicating that the element is moved down to clear past left floats.

Is a keyword indicating that the element is moved down to clear past right floats.

Is a keyword indicating that the element is moved down to clear past both left and right floats.

Is a keyword indicating that the element is moved down to clear floats on start side of its containing block, that is the left floats on ltr scripts and the right floats on rtl scripts.

Is a keyword indicating that the element is moved down to clear floats on end side of its containing block, that is the right floats on ltr scripts and the left floats on rtl scripts.

Formal definition

Formal syntax

clear =
inline-start |
inline-end |
block-start |
block-end |
left |
right |
top |
bottom |
none

Examples

clear: left

HTML

div class="wrapper"> p class="black"> Lorem ipsum dolor sit amet, consectetuer adipiscing elit. Phasellus sit amet diam. Duis mattis varius dui. Suspendisse eget dolor. p> p class="red">Lorem ipsum dolor sit amet, consectetuer adipiscing elit.p> p class="left">This paragraph clears left.p> div> 

CSS

.wrapper  border: 1px solid black; padding: 10px; > .left  border: 1px solid black; clear: left; > .black  float: left; margin: 0; background-color: black; color: #fff; width: 20%; > .red  float: left; margin: 0; background-color: pink; width: 20%; > p  width: 50%; > 

clear: right

HTML

div class="wrapper"> p class="black"> Lorem ipsum dolor sit amet, consectetuer adipiscing elit. Phasellus sit amet diam. Duis mattis varius dui. Suspendisse eget dolor. p> p class="red">Lorem ipsum dolor sit amet, consectetuer adipiscing elit.p> p class="right">This paragraph clears right.p> div> 

CSS

.wrapper  border: 1px solid black; padding: 10px; > .right  border: 1px solid black; clear: right; > .black  float: right; margin: 0; background-color: black; color: #fff; width: 20%; > .red  float: right; margin: 0; background-color: pink; width: 20%; > p  width: 50%; > 

clear: both

HTML

div class="wrapper"> p class="black"> Lorem ipsum dolor sit amet, consectetuer adipiscing elit. Phasellus sit amet diam. Duis mattis varius dui. Suspendisse eget dolor. Fusce pulvinar lacus ac dui. p> p class="red"> Lorem ipsum dolor sit amet, consectetuer adipiscing elit. Phasellus sit amet diam. Duis mattis varius dui. Suspendisse eget dolor. p> p class="both">This paragraph clears both.p> div> 

CSS

.wrapper  border: 1px solid black; padding: 10px; > .both  border: 1px solid black; clear: both; > .black  float: left; margin: 0; background-color: black; color: #fff; width: 20%; > .red  float: right; margin: 0; background-color: pink; width: 20%; > p  width: 45%; > 

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 Jul 18, 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.

Источник

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

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

Ширина элементов

Если обтекаемые элементы будет занимать всю доступную ширину, то остальные элементы, следующие за ними, будут начинаться с новой строки. Для этого суммарная ширина элементов должна равняться 100%. В примере 1 показано создание стрелок на одной строке.

Пример 1. Использование width

Каждый блок со стрелкой теперь занимает ширину 50% и в сумме они дают 100% ширины, поэтому абзац, идущий после arrow , начинается с новой строки.

Данный метод применяется редко, поскольку не всегда можно явно указать ширину элементов, к тому же метод не решает проблему с высотой блока и его фоном (рис. 1).

Нет фоновой заливки

Рис. 1. Нет фоновой заливки

Использование overflow

Свойство overflow управляет отображением содержимого блока, если оно целиком не помещается и выходит за область заданных размеров. Значение auto , в частности, добавляет полосы прокрутки при необходимости, а hidden отображает только область внутри элемента, остальное скрывает. Кроме этого, использование overflow со значением auto , scroll или hidden отменяет действие float (пример 2).

Пример 2. Применение overflow

Результат после применения свойства overflow сразу меняется (рис. 2).

Влияние свойства overflow на фон

Рис. 2. Влияние свойства overflow на фон

overflow — одно из самых популярных свойств, работающее в связке со свойством float . Но иногда возникают ситуации, когда применение этого метода недопустимо. Это происходит в тех случаях, когда элемент выходит за пределы блока, при этом он будет «обрезан». В примере 3 картинка сдвигается влево от своего исходного положения.

Пример 3. Обрезание области элемента

Сдвигаем картинку

Винни-Пух в гостях у Кролика

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

Обрезание картинки

Свойство clear

Для отмены действия float от вышестоящего элемента применяется свойство clear со следующими значениями:

  • left — отменяет действие значения left у float ;
  • right — отменяет действие значения right у float ;
  • both — одновременно отменяет действие значений left и right у float . Это значение рекомендуется устанавливать, когда требуется отменить обтекание элемента, но неизвестно точно с какой стороны.

Чтобы отменить действие обтекания, свойство clear надо добавлять к элементу, идущему после элемента с float . Обычно вводят универсальный класс, к примеру, clearfix и вставляют пустой с этим классом (пример 4).

Пример 4. Использование clear

section < border: 1px solid #000; /* Рамка */ padding: 10px; /* Поля вокруг текста */ >.fig < float: left; margin-right: 10px; >.clearfix

Винни-Пух в гостях у Кролика

В данном примере для класса clearfix установлено свойство clear со значением both .

Использование clear является одним из самых популярных в вёрстке в силу простоты и универсальности. Но иногда возникают комбинации, в которых использование clear даёт сбой. Это происходит, когда в коде встречается одновременно несколько разных обтекаемых элементов. Так, в примере 5 с помощью float создаются две колонки, а в правой колонке float упорядочивает фотографии.

Пример 5. Использование clear

.col1, .col2, footer < padding: 10px; >.col1 < float: left; width: 100px; background: #E8D9A9; >.col2 < margin-left: 120px; background: #ECC0A4; >.photo < border: 1px solid #333; text-align: center; background: #fff; float: left; padding: 10px; >.clearfix < clear: both; >footer

По годам

По рейтингу

По комментариям

Софийский собор
Польский костёл
Новая строка

Подвал

Результат примера показан на рис. 4. Свойство clear действует не только на класс photo , но и на класс col1 , т. е. на все элементы выше, у которых установлено float . Поэтому «Новая строка» начинается не сразу же после фотографий, а после завершения левой колонки.

Ошибка с отображением строки

Рис. 4. Ошибка с отображением строки

В подобных ситуациях помогает комбинация разных методов. Так, фотографии можно добавить в контейнер с overflow и удалить clearfix . Колонка приобретёт следующий вид.

Софийский собор
Польский костёл

Новая строка

Псевдоэлемент ::after

Частое включение пустого элемента со свойством clear захламляет код, особенно при активном использовании свойства float . Логично перенести всё в стили, избавившись от лишних элементов. Для этого воспользуемся псевдоэлементом ::after, который в комбинации со свойством content добавляет пустой текст после содержимого элемента. К такому тексту можно применить стилевые свойства, в частности clear .

Вместо значения block у display иногда вставляют значение table , но смысл это не меняет, так же как и набор других возможных свойств. Их задача — создать невидимый блок, который будет отменять действие float у вышестоящих элементов.

Поскольку текст, генерируемый через псевдоэлемент ::after , располагается после содержимого элемента, он с лёгкостью заменяет конструкцию . Там, где она требуется достаточно только добавить класс clearfix , как показано в примере 6.

Пример 6. Псевдоэлемент ::after

Сдвигаем картинку

section < border: 1px solid #000; /* Рамка */ padding: 10px; /* Поля вокруг текста */ >.fig < float: left; margin-right: 10px; >.clearfix::after

Винни-Пух в гостях у Кролика

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

Источник

Читайте также:  Java создать json строку
Оцените статью