Изменение размеров в CSS
In the various lessons so far you have come across a number of ways to size items on a web page using CSS. Understanding how big the different features in your design will be is important, and in this lesson we will summarize the various ways elements get a size via CSS and define a few terms around sizing that will help you in the future.
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 the different ways we can size things in CSS. |
The natural or intrinsic size of things
HTML Elements have a natural size, set before they are affected by any CSS. A straightforward example is an image. An image has a width and a height defined in the image file it is embedding into the page. This size is described as the intrinsic size — which comes from the image itself.
If you place an image on a page and do not change its height and width, either using attributes on the tag or CSS, it will be displayed using that intrinsic size. We have given the image in the example below a border so that you can see the extent of the file.
In the example above, try adding some text inside the empty element. The border now contains that text because the height of the element is defined by the content. Therefore the size of this
Setting a specific size
We can of course give elements in our design a specific size. When a size is given to an element (and the content of which then needs to fit into that size) we refer to it as an extrinsic size. Take our
Due to this problem of overflow, fixing the height of elements with lengths or percentages is something we need to do very carefully on the web.
Using percentages
In many ways percentages act like length units, and as we discussed in the lesson on values and units, they can often be used interchangeably with lengths. When using a percentage you need to be aware what it is a percentage of. In the case of a box inside another container, if you give the child box a percentage width it will be a percentage of the width of the parent container.
This is because percentages resolve against the size of the containing block. With no percentage applied our
Percentage margins and padding
If you set margins and padding as a percentage you may notice some strange behavior. In the below example we have a box. We have given the inner box a margin of 10% and a padding of 10%. The padding and margin on the top and bottom of the box are the same size as the margin on the left and right.
You might expect for example the percentage top and bottom margins to be a percentage of the element’s height, and the percentage left and right margins to be a percentage of the element’s width. However, this is not the case!
When you use margin and padding set in percentages, the value is calculated from the inline size — therefore the width when working in a horizontal language. In our example, all of the margins and padding are 10% of the width. This means you can have equal sized margins and padding all round the box. This is a fact worth remembering if you do use percentages in this way.
min- and max- sizes
In addition to giving things a fixed size, we can ask CSS to give an element a minimum or a maximum size. If you have a box that might contain a variable amount of content, and you always want it to be at least a certain height, you could set the min-height property on it. The box will always be at least this height, but will then grow taller if there is more content than the box has space for at its minimum height.
In the example below you can see two boxes, both with a defined height of 150 pixels. The box on the left is 150 pixels tall; the box on the right has content that needs more room, and so it has grown taller than 150 pixels.
This is very useful for dealing with variable amounts of content while avoiding overflow.
A common use of max-width is to cause images to scale down if there is not enough space to display them at their intrinsic width, while making sure they don’t become larger than that width.
As an example, if you were to set width: 100% on an image, and its intrinsic width was smaller than its container, the image would be forced to stretch and become larger, causing it to look pixellated. If its intrinsic width were larger than its container, it would overflow it. Neither case is likely to be what you want to happen.
If you instead use max-width: 100% , the image is able to become smaller than its intrinsic size, but will stop at 100% of its size.
In the example below we have used the same image twice. The first image has been given width: 100% and is in a container which is larger than it, therefore it stretches to the container width. The second image has max-width: 100% set on it and therefore does not stretch to fill the container. The third box contains the same image again, also with max-width: 100% set; in this case you can see how it has scaled down to fit into the box.
This technique is used to make images responsive, so that when viewed on a smaller device they scale down appropriately. You should however not use this technique to load in really large images and then scale them down in the browser. Images should be appropriately sized to be no larger than they need to be for the largest size they are displayed in the design. Downloading overly large images will cause your site to become slow, and it can cost users more money if they are on a metered connection.
Note: Find out more about responsive image techniques.
Viewport units
The viewport — which is the visible area of your page in the browser you are using to view a site — also has a size. In CSS we have units which relate to the size of the viewport — the vw unit for viewport width, and vh for viewport height. Using these units you can size something relative to the viewport of the user.
1vh is equal to 1% of the viewport height, and 1vw is equal to 1% of the viewport width. You can use these units to size boxes, but also text. In the example below we have a box which is sized as 20vh and 20vw. The box contains a letter A , which has been given a font-size of 10vh.
If you change the vh and vw values this will change the size of the box or font; changing the viewport size will also change their sizes because they are sized relative to the viewport. To see the example change when you change the viewport size you will need to load the example in a new browser window that you can resize (as the embedded that contains the example shown above is its viewport). Open the example, resize the browser window, and observe what happens to the size of the box and text.
Sizing things according to the viewport can be useful in your designs. For example, if you want a full page hero section to show before the rest of your content, making that part of your page 100vh high will push the rest of the content below the viewport, meaning that it will only appear once the document is scrolled.
Summary
This lesson has given you a rundown of some key issues that you might run into when sizing things on the web. When you move onto CSS Layout, sizing will become very important in mastering the different layout methods, so it is worth understanding the concepts here before moving on.
Умная адаптация ширины блочных элементов на чистом CSS 2.0
Верстая очередной проект (или ещё только проектируя макетную сетку) многие сталкивались с дилеммой — использовать фиксированную ширину макета или «резиновую» сетку, адаптируемую под размер окна браузера.
У каждого из этих решений есть свои плюсы и минусы, хочу заострить внимание на минусах, так как обычно именно между двух зол именно в отражении минусов этих решений приходится выбирать.
Фиксированная ширина макетной сетки
Вёрстку загоняют в горизонтальный габарит 960—980 пикселей (чтобы на большинстве устройств в большинстве разрешений всё входило), что при больших горизонтальных размерах окна выглядит как-то зябко — тонкая вертикальная полоса полезного содержимого страницы и огромные бесполезные поля неиспользуемого пространства по бокам.
«Резиновая» макетная сетка по ширине окна
Опять же при больших горизонтальных размерах окна есть другая проблема: строки текста становятся очень длинными, и читать их становится совсем не так комфортно, как хотелось бы.
Ещё одна распространённая проблема этого решения — боковые отступы при больших горизонтальных размерах окна уже не так удачно визуально согласуются с горизонтальными размерами элементов, что также не добавляет комфорта при взгляде на свёрстанный макет.
Хочу предложить нехитрый вариант решения — ограничить минимальный горизонтальный размер фиксированным значением в пикселях, а максимальный сделать относительным в процентном соотношении к ширине окна. Это очень банально решается простыми средствами ещё 2 версии спецификации CSS.
Update: Хочу оговориться, что речь не идёт о классическом эффекте резины и об адаптации под абсолютно все разрешения, скорее лишь про некий разумный диапазон разрешений, под который проектируется макет. В примерах ниже — это классический десктопный диапазон разрешений с горизонтальным габаритом разрешения от 1024 пикселей.
Ещё раз акцентирую внимание: в посте не идёт речь про решение для всех видов устройств и все диапазоны разрешений. В рамках одного макета эта задача не решаема в принципе, для её решения так или иначе потребуется несколько макетов. Мухи отдельно, котлеты отдельно.
Создаём контейнер макета:
Оформляем его незатейливым кодом стиля:
Однако этого решения кому-то может показаться мало в силу того что при очень больших горизонтальных размерах окна опять проявляются проблемы с длиной строк. Это решается настолько же простым дополнительным приёмом: создание дополнительного внешнего контейнера внутри уже описанного и ограничение его максимальной ширины фиксированным значением (мне субъективно кажется, что лучше всего подходят значния в диапазоне 1400—1600 пикселей). Опять же используем лишь средства CSS 2.0. Такое решение вместо предложенного в первом комментарии простого добавления ширины в процентах для исходного контейнера будет работать ещё и в IE, который вплоть до 9 версии не понимает одновременного указания значений.
И немного меняем CSS:
Как видите — решение предельно просто и достаточно универсально, может применяться для любых блочных элементов.
Make body have 100% of the browser height
I want to make body have 100% of the browser height. Can I do that using CSS?
I tried setting height: 100% , but it doesn’t work.
I want to set a background color for a page to fill the entire browser window, but if the page has little content I get a ugly white bar at the bottom.
23 Answers 23
Try setting the height of the html element to 100% as well.
Body looks to its parent (HTML) for how to scale the dynamic property, so the HTML element needs to have its height set as well.
However the content of body will probably need to change dynamically. Setting min-height to 100% will accomplish this goal.
As an alternative to setting both the html and body element’s heights to 100% , you could also use viewport-percentage lengths.
The viewport-percentage lengths are relative to the size of the initial containing block. When the height or width of the initial containing block is changed, they are scaled accordingly.
In this instance, you could use the value 100vh — which is the height of the viewport.
This is supported in most modern browsers — support can be found here.
If you have a background image then you will want to set this instead:
This ensures that your body tag is allowed to continue growing when the content is taller than the viewport and that the background image continues to repeat/scroll/whatever when you start scrolling down.
Remember if you have to support IE6 you will need to find a way to wedge in height:100% for body, IE6 treats height like min-height anyway.
If you want to keep the margins on the body and don’t want scroll bars, use the following css:
Setting body
After testing various scenarios, I believe this is the best solution:
It is dynamic in that the html and the body elements will expand automatically if their contents overflow. I tested this in the latest version of Firefox, Chrome, and IE 11.
See the full fiddle here (for you table haters out there, you can always change it to use a div):
With that being said, there are several issues with the answers posted here.
Using the above CSS will cause the html and the body element to NOT automatically expand if their contents overflow as shown here:
As you scroll, notice the repeating background? This is happening because the body element’s height has NOT increased due to its child table overflowing. Why doesn’t it expand like any other block element? I’m not sure. I think browsers handle this incorrectly.
Setting a min-height of 100% on the body as shown above causes other problems. If you do this, you cannot specify that a child div or table take up a percentage height as shown here:
Hope this helps someone. I think browsers are handling this incorrectly. I would expect the body’s height to automatically adjust growing larger if its children overflow. However, that doesn’t seem to happen when you use 100% height and 100% width.
A better solution with today’s CSS
What I use on the start of literally every CSS file I use is the following:
The margin of 0 ensures that the HTML and BODY elements aren’t being auto-positioned by the browser to have some space to the left or right of them.
The padding of 0 ensures that the HTML and BODY elements aren’t automatically pushing everything inside them down or right because of browser defaults.
The width and height variants are set to 100% to ensure that the browser doesn’t resize them in anticipation of actually having an auto-set margin or padding, with min and max set just in case some weird, unexplainable stuff happens, though you probably dont need them.
This solution also means that, like I did when I first started on HTML and CSS several years ago, you won’t have to give your first
Before I posted, I looked at my other fullscreen CSS project and found that all I used there was just body
Hope this detailed answer helps, and I feel your pain. In my eyes, it is dumb that browsers should set an invisible boundary on the left and sometimes top side of the body/html elements.
You can also use JS if needed
Please check this:
Or try new method Viewport height :
Viewport: If your using viewport means whatever size screen content will come full height fo the screen.
If you don’t want the work of editing your own CSS file and define the height rules by yourself, the most typical CSS frameworks also solve this issue with the body element filling the entirety of the page, among other issues, at ease with multiple sizes of viewports.
For example, Tacit CSS framework solves this issue out of the box, where you don’t need to define any CSS rules and classes and you just include the CSS file in your HTML.
I would use this
The browser will use min-height: 100vh and if somehow the browser is a little older the min-height: 100% will be the fallback.
The overflow: auto is necessary if you want the body and html to expand their height when you resize the screen (to a mobile size for example)
Works for all major browsers: FF, Chrome, Opera, IE9+. Works with Background images and gradients. Scrollbars are available as content needs.
Only with 1 line of CSS… You can get this done.
all answers are 100% correct and well explained, but i did something good and very simple to make it responsive.
here the element will take 100% height of view port but when it comes to mobile view it don’t look good specially on portrait view ( mobile ), so when view port is getting smaller the element will collapse and overlap on each other. so to make it little responsive here is code. hope someone will get help from this.
There are some good answers here but also some misunderstandings. I support the following settings for modern browsers when styling for dimensions in web pages:
For starters, the new viewport units («vh») are redundant and not necessary as long as you have set html to a height of 100% . The reason is the body derives its values from the html parent. You can still use «vh» units in body to bypass the parent and get its property dimensions directly from the viewport. But its optional if html has 100% height.
Notice I’ve set body to height:auto . You do NOT want to set body height and width to 100% , or specific values as that limits content to the viewport’s dimensions and there will be overflow. height:auto is your best friend in CSS! Using overflow:auto properties are not needed if you set height:auto on the body . That tells the page to let content expand height to any dimension necessary, even that beyond the viewport’s height, if it needs to. It will not break out of the body dimensions. And it does allow scrolling as needed. auto also allows you to have margins and still support pages that fill the viewport using min-height . I believe height:auto is the default on body in most UA browser style sheets, anyway.
Adding min-height:100% then gives you the default height you want body to have and then allows the page dimensions to fill the viewport without content breaking out of the body. This works only because html has derived its height:100% based on the viewport.
The two CRITICAL pieces here are not the units, like % or vh , but making sure the root element, or html , is set to 100% of the viewport height. Second, its important that body have a min-height:100% or min-height:100vh so it starts out filling the viewport height, whatever that may be. Nothing else beyond that is needed. Notice I have added «fallback» properties for min-height, as many browsers post-2010 do not support «vh» units. Its fun to pretend everyone in the web world uses the latest and greatest but the reality is many legacy browsers are still around today in big corporate networks still use antiquated browsers that do not understand those new units.
STYLING HEIGHT FOR LEGACY BROWSERS
One of the things we forget is many very old browsers do not know how to fill the the viewport height correctly. Sadly, those legacy browsers simply had to have height:100% on both the html element and the body . If you did not do that, browser background colors and other weird visuals would flow up under content that did not fill the viewport. We solved that by delivering these 100% values only to older user-agents. If you are testing on a legacy browser, keep that in mind.