В этом уроке мы рассмотрим другую важную концепцию в CSS — overflow. Overflow это то что случается, когда слишком много контента содержится внутри блока. В этом гайде вы изучите что это и как этим управлять.
|Prerequisites:||Basic computer literacy, basic software installed, basic knowledge of working with files, HTML basics (study Introduction to HTML), and an idea of how CSS works (study CSS first steps.)|
|Objective:||To understand overflow and how to manage it.|
Мы уже знаем что все в CSS - блоки, и что мы можем ограничивать размер этих блоков присваивая им определенное значение посредством
block-size). Overflow это то что случается, когда у вас слишком много контента в блоке, так что он не помещается в данный ограниченный блок. CSS дает нам различные инструменты для управления этим overflow, и это также полезная концепция для понимания на этой ранней стадии. Вы будете встречаться с overflow достаточно часто когда пишите CSS, особенно когда глубже погрузитесь в CSS макет.
Давайте начнем с рассмотрения двух примеров, которые демонстрируют как CSS ведет себя когда у вас overflow.
The first is a box that has been restricted in the block dimension by giving it a
height. We have then added more content than there is space for in this box. The content is overflowing the box and laying itself rather messily over the paragraph below the box.
The second is a word in a box that is restricted in the inline dimension. The box has been made too small for that word to fit and so it breaks out of the box.
You might wonder why CSS has by default taken the rather untidy approach of causing the content to overflow messily? Why not hide the additional content, or cause the box to grow?
Wherever possible CSS does not hide your content; to do so would cause data loss, which is usually a problem. In CSS terms, this means some content vanishing. The problem with content vanishing is that you might not notice it has vanished. Your visitors may not notice it has vanished. If it is the submit button on a form that disappears, and no-one can complete the form, that's a big problem! So instead, CSS tends to overflow in a visible way. It is likely you will see the mess, or at worst a visitor to your site will let you know that some content is overlapping so it needs fixing.
If you have restricted a box with a
width or a
height, CSS assumes you know what you are doing, and that you are managing the potential for overflow. In general, restricting the block dimension is problematic when text is going to be put in a box, as there may be more text than you expected when designing the site or the text may be bigger — for example if the user has increased their font size.
In the next couple of lessons we will look at different ways to control sizing that might be less prone to overflow. However, if you need a fixed size you can also control how the overflow behaves. Let's read on!
overflow property is how you take control of an element's overflow and tell the browser how you want it to behave. The default value of overflow is
visible, which is why by default we can see our content when it overflows.
If you want to crop the content when it overflows you can set
overflow: hidden on your box. This will do exactly what it says — hide the overflow. This may well cause things to vanish so you should only ever do this if hiding content is not going to cause a problem.
Perhaps you would instead like to add scrollbars when content overflows? If you use
overflow: scroll then your browser will always display scrollbars — even if there is not enough content to overflow. You may want this, as it prevents scrollbars appearing and disappearing depending on content.
If you remove some of the content from the box below, you'll see that the scrollbars still remain even with nothing to scroll (or at least just the scrollbar tracks).
In the above example we only need to scroll on the
y axis, however we get scrollbars in both axes. You could instead use the
overflow-y property, setting
overflow-y: scroll to only scroll on the
You could also scroll on the x axis using
overflow-x, although this is not a recommended way to deal with long words! If you do need to deal with a long word in a small box then you could look at the
overflow-wrap properties. In addition some of the methods discussed in the Sizing items in CSS lesson may help you to create boxes that cope better with varying amounts of content.
scroll, you will get a scrollbar in the scrolling dimension whether or not there is enough content to cause a scrollbar.
Note: that you can specify x and y scrolling using the
overflow property and passing in two values. If two keywords are specified, the first applies to
overflow-x and the second to
overflow-y. Otherwise, both
overflow-y are set to the same value. For example,
overflow: scroll hidden would set
If you only want scrollbars to appear if there is more content than can fit in the box, then use
overflow: auto. In this case it is left up to the browser to decide whether to display scrollbars. Desktop browsers will typically only do so once there is enough content to cause overflow.
In the below example, remove some of the content until it fits into the box and you should see the scrollbars disappear.
There is a concept in CSS of the Block Formatting Context (BFC). This isn't something you need to worry too much about right now, but it is useful to know that when you use a value of overflow such as
auto you create a BFC. The result is that the content of the box you have changed the value of
overflow for becomes a mini layout of its own. Things outside the container cannot poke into the container, and nothing can poke out of that box into the surrounding layout. This is to enable the scrolling behavior, as all content of your box will need to be contained and not overlap other items on the page, in order to create a consistent scrolling experience.
Modern layout methods (as covered in the CSS layout module) manage overflow very well. They have been designed to cope with the fact that we tend not to be able to predict how much content we have on the web. In the past however, developers would often use fixed heights to try to line up the bottoms of boxes that really had no relationship to each other. This was fragile, and in a legacy application you may occasionally come across a box where the content is overlaying other content on the page. If you see this you now know that what is happening is overflow; ideally you would refactor the layout to not rely on fixing the box size.
When developing a site you should always keep overflow issues in mind. You should test designs with large and small amounts of content, increase the font size of text and ensure that your CSS can cope in a robust way. Changing the value of overflow to hide content or add scrollbars is likely to be something you reserve only for a few special cases — where you really do want a scrolling box for example.
This short lesson has introduced the concept of overflow; you now understand that CSS tries not to make overflowing content invisible as this will cause data loss. You have discovered that you can manage potential overflow, and also that you should test your work to make sure you do not accidentally cause problematic overflow.
- Cascade and inheritance
- CSS selectors
- The box model
- Backgrounds and borders
- Handling different text directions
- Overflowing content
- Values and units
- Sizing items in CSS
- Images, media, and form elements
- Styling tables
- Debugging CSS
- Organizing your CSS