- DIV блоки с float: left; трабл с height
- Особенности свойства height в %
- Пример
- Демо height:100% + float:left
- DIV блоки с float: left; трабл с height
- float
- Try it
- Syntax
- Values
- Formal definition
- Formal syntax
- Examples
- How floated elements are positioned
- HTML
- CSS
- Result
- Clearing floats
- Specifications
- Browser compatibility
- See also
- Found a content problem with this page?
DIV блоки с float: left; трабл с height
Всем привет!
Есть 2 DIV’а завернутые в другой DIV.
Суть проблемы:
При пустом левом блоке правый отображается нормально на 100%, но стоит только хоть одну букву внести в левый блок, как правый тут же теряет height свой.
div class="bob"> div class="news"> /div> div class="r_side"> h1>Новости/h1> p>Тута какойнить текст/p> /div> /div>
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28
.bob{ min-height: 100%; width: 100%; background-color: #eaeaea; display: table; } .news{ min-height: 100%; width: 860px; margin: 3px auto; float: left; } /* Right -----------------------------------------------------------------------------*/ .r_side{ height: 100%; min-height: 50px; width: 280px; float: left; margin-left: 10px; background-color: #f6f6f6; border: 2px solid #53669d; padding: 5px; border-radius: 15px; box-shadow: 0 0 15px #53669d; word-break: break-all; }
Как выравнить по высоте div блоки со свойством float: left?
Всем привет! Я только учусь css, и столкнулся с проблемой в выравнивании div блоков по высоте.
Верстка блоков с float:left и общим min-height
Здравствуйте, облазил уже кучу форумов, но ответа так и на нашел. Верстка примерно такая <div.
Блоки по центру с float:left
Надо разместить блоки по центру, с ПРОЦЕНТНОЙ шириной, margin:20px, border:1px.
float:left и блоки с закруглёнными углами
Проблема в следующем:когда я размещаю 2 diva с закруглёнными углами рядом друг с другом,и указываю.
А что вы хотите? Сделать так, чтобы они отображались в одном ряду?
Уменьшите ширину у левого блока.
Да, это две колонки рядом. ширины достаточно.
Добавлено через 4 минуты
Проблема решилась, был косяк в min-height.
Спасибо за ответ.
Проблема актуальна=) ничего не решилось(
Если контент левого блока не превышает высоту высоту в 100% — правый блок отображается нормально на 100%, как только превышает — правый блок теряет height.
Особенности свойства height в %
Обычно свойство height , указанное в процентах, означает высоту относительно внешнего блока.
Однако, всё не так просто. Интересно, что для произвольного блочного элемента height в процентах работать не будет!
Чтобы лучше понимать ситуацию, рассмотрим пример.
Пример
Наша цель – получить вёрстку такого вида:
При этом блок с левой стрелкой должен быть отдельным элементом внутри контейнера.
Это удобно для интеграции с JavaScript, чтобы отлавливать на нём клики мыши.
То есть, HTML-код требуется такой:
Как это реализовать? Подумайте перед тем, как читать дальше…
Придумали. Если да – продолжаем.
Есть разные варианты, но, возможно, вы решили сдвинуть .toggler влево, при помощи float:left (тем более что он фиксированной ширины) и увеличить до height: 100% , чтобы он занял всё пространство по вертикали.
Вы ещё не видите подвох? Смотрим внимательно, что будет происходить с height: 100% …
Демо height:100% + float:left
.container < border: 1px solid black; >.content < /* margin-left нужен, так как слева от содержимого будет стрелка */ margin-left: 35px; >.toggler < /* Зададим размеры блока со стрелкой */ height: 100%; width: 30px; float: left; background: #EEE url("arrow_left.png") center center no-repeat; border-right: #AAA 1px solid; cursor: pointer; >
А теперь – посмотрим этот вариант в действии:
Как видно, блок со стрелкой вообще исчез! Куда же он подевался?
Ответ нам даст спецификация CSS 2.1 пункт 10.5.
«Если высота внешнего блока вычисляется по содержимому, то высота в % не работает, и заменяется на height:auto . Кроме случая, когда у элемента стоит position:absolute .»
В нашем случае высота .container как раз определяется по содержимому, поэтому для .toggler проценты не действуют, а размер вычисляется как при height:auto .
Какая же она – эта автоматическая высота? Вспоминаем, что обычно размеры float определяются по содержимому (10.3.5). А содержимого-то в .toggler нет, так что высота нулевая. Поэтому этот блок и не виден.
Если бы мы точно знали высоту внешнего блока и добавили её в CSS – это решило бы проблему.
DIV блоки с float: left; трабл с height
Всем привет!
Есть 2 DIV’а завернутые в другой DIV.
Суть проблемы:
При пустом левом блоке правый отображается нормально на 100%, но стоит только хоть одну букву внести в левый блок, как правый тут же теряет height свой.
div class="bob"> div class="news"> /div> div class="r_side"> h1>Новости/h1> p>Тута какойнить текст/p> /div> /div>
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28
.bob{ min-height: 100%; width: 100%; background-color: #eaeaea; display: table; } .news{ min-height: 100%; width: 860px; margin: 3px auto; float: left; } /* Right -----------------------------------------------------------------------------*/ .r_side{ height: 100%; min-height: 50px; width: 280px; float: left; margin-left: 10px; background-color: #f6f6f6; border: 2px solid #53669d; padding: 5px; border-radius: 15px; box-shadow: 0 0 15px #53669d; word-break: break-all; }
Как выравнить по высоте div блоки со свойством float: left?
Всем привет! Я только учусь css, и столкнулся с проблемой в выравнивании div блоков по высоте.
Верстка блоков с float:left и общим min-height
Здравствуйте, облазил уже кучу форумов, но ответа так и на нашел. Верстка примерно такая <div.
Блоки по центру с float:left
Надо разместить блоки по центру, с ПРОЦЕНТНОЙ шириной, margin:20px, border:1px.
float:left и блоки с закруглёнными углами
Проблема в следующем:когда я размещаю 2 diva с закруглёнными углами рядом друг с другом,и указываю.
А что вы хотите? Сделать так, чтобы они отображались в одном ряду?
Уменьшите ширину у левого блока.
Да, это две колонки рядом. ширины достаточно.
Добавлено через 4 минуты
Проблема решилась, был косяк в min-height.
Спасибо за ответ.
Проблема актуальна=) ничего не решилось(
Если контент левого блока не превышает высоту высоту в 100% — правый блок отображается нормально на 100%, как только превышает — правый блок теряет height.
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.