- Не работает вертикальный скролл в flex
- 1 ответ 1
- Всё ещё ищете ответ? Посмотрите другие вопросы с метками html css или задайте свой вопрос.
- Похожие
- Подписаться на ленту
- overflow:scroll not working on flex items
- 3 Answers 3
- Not the answer you’re looking for? Browse other questions tagged html css flexbox or ask your own question.
- Related
- Hot Network Questions
- Subscribe to RSS
- a-x- / scroll-in-flex.md
- How to Fix Overflow Issues in CSS Flex Layouts
- The Setup
- The Results
- CodePen
- Conclusion
- firefox overflow-y not working with nested flexbox
- 2 Answers 2
Не работает вертикальный скролл в flex
Делаю чатик, функционал уже готов, только вот не получилось сделать вертикальный скролл. Сам скролл я добавил overflow-y: scroll а вот сообщения всё равно не скроллят. Когда я убираю display: flex скролл начинает работать, только всё из-за этого начинает ехать.
1 ответ 1
Логику поведения не понял, но решить удалось следующими действиями:
- элементу #messages (родителю «сообщений») задаём min-height: 100% , а не height , ну и убираем от него overflow .
- А вот родителю #messages ( .chat-body , а лучше создать «элемент обёртку») выдаём уже ограничение по высоте (если надо) и overflow-y: scroll
Всё ещё ищете ответ? Посмотрите другие вопросы с метками html css или задайте свой вопрос.
Похожие
Подписаться на ленту
Для подписки на ленту скопируйте и вставьте эту ссылку в вашу программу для чтения RSS.
дизайн сайта / логотип © 2021 Stack Exchange Inc; материалы пользователей предоставляются на условиях лицензии cc by-sa. rev 2021.10.18.40487
Нажимая «Принять все файлы cookie» вы соглашаетесь, что Stack Exchange может хранить файлы cookie на вашем устройстве и раскрывать информацию в соответствии с нашей Политикой в отношении файлов cookie.
Источник
overflow:scroll not working on flex items
I have three div’s:
- Div 01
- Div 02 — fixed width 300px
- Div 03
Div 01 and Div 03 should be same width.
- If viewport is 1000px, Div 01 width=350px and Div 03 width=350px,
- If viewport is 800px, Div 01 width=250px and Div 03 width=250px.
This is work as I want. But I need to add overflow: scroll to flex-item class.
After adding this, it does not work. How to solve it?
3 Answers 3
If you want Div 01 and Div 03 to be the same width, then flex: 1 auto is not a reliable tool. The flex-grow: 1 component will size the flex item based on the available space in the container, which could vary. You need to define a width for the flex-item class.
For the flex items to scroll vertically, you need to specify a height or flex-basis (when flex-direction is column ).
For the flex items to scroll horizontally, you need to specify width or flex-basis (when flex-direction is row ). You also need to add white-space: nowrap .
When you use flexbox all your div need to be in the flex flow.
So you better use flex: 1 1 300px instead of width: 300px
This fiddle can help you! To make overflow:scroll work use the below attributes:
Not the answer you’re looking for? Browse other questions tagged html css flexbox or ask your own question.
Related
Hot Network Questions
Subscribe to RSS
To subscribe to this RSS feed, copy and paste this URL into your RSS reader.
site design / logo © 2021 Stack Exchange Inc; user contributions licensed under cc by-sa. rev 2021.10.18.40487
By clicking “Accept all cookies”, you agree Stack Exchange can store cookies on your device and disclose information in accordance with our Cookie Policy.
Источник
a-x- / scroll-in-flex.md
Как поместить scroll -контейнер во flexbox и не облажаться.
Столкнулись с проблемой: блок со скролом распепячивает flex. Давайте разбираться.
4 месяца назад показалось, что хак найден, о чём мы поспешили рассказать в твиттере, но потом стало ясно что таки поспешили.
Помотрели в спеку и mdn, но ключей к решению не нашли.
MDN: In order for overflow to have an effect, the block-level container must have either a set height (height or max-height) or white-space set to nowrap.
После экспериментов (демки ниже) стало понятно что приводит к растяжению ширины scroll -контейнера: родительские flex-контейнеры без заданной через width ширины, см. сниппет 1.4. Ширина-то необходима как следует из статьи с MDN.
Но очевидно, задание width элементу flex-контейнера ломает flex-поведение, см. сниппеты 1.6. и 2.2.
А коли во flex мы не имеем права задавать width , то и scroll справедливо не работает.
Слава Гридам, был найден ХАК: Если обернуть scroll в грид из одного элемента, то задавать ширину или white-space , как указано в документации не трубуется, см. сниппет 0.0.
Демки в порядке дебага
1. Попытка сломать простой работающий скрол внутри ширины в %
- ❎ Just overflow
- ❎ Just overflow in flex wrap
- ❎ Just overflow with single scrollable
- ссылка сломалась 👹 Minimal reproducing: after extra flex added!
- ссылка сломалась Fixed: .flex-wrap.inner
- ссылка сломалась But it’s broken at all
2. Попытка починить сломанное решение из проекта
- ссылка сломалась 🚩 Reproducing (copied from project)
- ссылка сломалась ✴️ Removing div.scroll-wrap fixes it! But width still overflows
- 🧡 With Grid hack
Ответы на вопросы
Почему просто не заворачивать всё в гриды
В динамических SPA компонентах содержимое может произвольным образом меняться, часто нельзя задавать в css жёсткую структуры. Хотя гриды и обладают гибкостью к содержимому контейнера (например, можно описать колонки для произвольного количества «строк»), часто это или излишне или всё же недостаточно гибко и требует дублировать знание о структуре динамического контента в css.
Где это нужно
Мы эту проблему решили для скролящихся вкладок внутри 2-х вложенных flex-контейнеров составной шапки. Эта шапка состоит из родительского React-компонента, описывающего компоновку (layout) и встроенного фрагмента, специфичного для этого типа страниц.
Зачем в демках два вложенных флекса
Например .scroll-wrap-2 это прекрасный пример хака «scrollbar-hider»: прячущего скролбар внизу для любой платформы. В других демках вложенные флексы демонструруют реальную структуры вёрстки боевого проекта состоящего из встроенных из вне компонент.
В следующей статье расскажем про хак с display: grid и position: sticky в главных ролях.
Эти результаты не стали бы реальностью без классных ребят из моей команды:
Источник
How to Fix Overflow Issues in CSS Flex Layouts
Want to read the how-to? Continue below!
I recently ran into an odd overflow problem in Firefox, Safari and Edge. I had a simple flex column layout that needed to scroll on overflow. It looked great on Chrome of course, but wouldn’t overflow on other browsers. The content would just expand to its full height and blow out the layout.
| Chrome | Firefox / Safari / Edge |
The Setup
The goal here was to create a list of content with a fixed header section above it. The list content was of an unknown length and would need to scroll. To make things a little more complicated, there was some additional content intertwined in the container divs and this entire component was destined to be used in several places.
“Easy,” I thought. I whipped up a quick flex-direction: column; container with a fixed div for the heading content and an overflow div container with its overflow content under that.
I tested in Chrome – looks great
I tested in Firefox and Safari – looks great.
I cleaned up the code, submitted the PR, and marked my ticket Ready for QA. Done.
…until a week later when the bug ticket came in. Scrolling wasn’t working in Firefox. …What?
The Results
Under certain circumstances overflow needs a little extra love. It turns out that there was a feature in the flexbox specification that added an implied minimum size for flex items. This feature was removed and then re-added back into the spec at some point.
Lucky for us, the fix is an easy one. Simply add min-height: 0; to the flex child that has our overflow container.
CodePen
Check out the code on CodePen.
Conclusion
It’s a super simple fix to an oddball edge case that took me a number of hours to find a solution for. Hopefully this saves you a bunch of time and hair pulling.
Play around with the CodePen, change things and make the knowledge your own. As always, if you have any comments or ideas to share, please leave them below or look me up on Twitter!
Источник
firefox overflow-y not working with nested flexbox
I have designed a 100% width 100% height layout with css3 flexbox, which works both on IE11 (and probably on IE10 if emulation of IE11 is correct).
But Firefox (35.0.1), overflow-y is not working. As you can see in this codepen : http://codepen.io/anon/pen/NPYVga
firefox is not rendering overflow correctly. It shows one scrollbar
2 Answers 2
tl;dr: you need min-height:0 in your .level-0-row2 rule. (Here’s a codepen with that fix.)
More detailed explanation:
Flex items establish a default minimum size that’s based on their children’s intrinsic size (which doesn’t consider «overflow» properties on their children/descendants).
Whenever you’ve got an element with overflow: [hidden|scroll|auto] inside of a flex item, you need to give its ancestor flex item min-width:0 (in a horizontal flex container) or min-height:0 (in a vertical flex container), to disable this min-sizing behavior, or else the flex item will refuse to shrink smaller than the child’s min-content size.
See https://bugzilla.mozilla.org/show_bug.cgi?id=1043520 for more examples of sites that have been bitten by this. (Note that this is just a metabug to track sites that were broken by this sort of issue, after this spec-text was implemented — it’s not actually a bug in Firefox.)
You won’t see this in Chrome (at least, not as of this posting) because they haven’t implemented this minimum sizing behavior yet. (EDIT: Chrome has now implemented this min-sizing behavior, but they may still incorrectly collapse min-sizes to 0 in some cases.)
Источник