Html element width height

Sizing items in 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. So, in this lesson we will summarize the various ways elements get a size via CSS and define a few terms about 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 file contains sizing information, described as its intrinsic size. This size is determined by the image itself, not by any formatting we happen to apply.

If you place an image on a page and do not change its height or width, either by using attributes on the tag or else by 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 its size as defined in its 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 in the block dimension comes from the size of the content. Again, this is the intrinsic size of the element — its size is defined by its content.

Setting a specific size

We can, of course, give elements in our design a specific size. When a size is given to an element (the content of which then needs to fit into that size) we refer to it as an extrinsic size. Take our from the example above — we can give it specific width and height values, and it will now have that size no matter what content is placed into it. As we discovered in our previous lesson on overflow, a set height can cause content to overflow if there is more content than the element has space to fit inside it.

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.

Читайте также:  Python get console arguments

This is because percentages resolve against the size of the containing block. With no percentage applied, our would take up 100% of the available space, as it is a block level element. If we give it a percentage width, this becomes a percentage of the space it would normally fill.

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 padding and 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 of the containing block — 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 around 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 min-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 pixelated.

If you instead use max-width: 100% , and its intrinsic width is smaller than its container, the image will not be forced to stretch and become larger, thus preventing pixelation.

In the example below, we have used the same image three times. 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.

Читайте также:  Native keyword in java

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 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.

Test your skills!

You’ve reached the end of this article, but can you remember the most important information? You can find some further tests to verify that you’ve retained this information before you move on — see Test your skills: Sizing.

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.

In the next article, we’ll take a look at how images, media, and form elements are treated in CSS.

Found a content problem with this page?

This page was last modified on Jun 30, 2023 by MDN contributors.

Читайте также:  Java what is an interface used for

Источник

Ширина (width) и высота (height) в HTML

В этой статье рассмотрим, как можно задавать ширину и какими свойствами стоит делать это. Для первого примера возьмём блочный элемент div. По умолчанию он имеет высоту равную нулю (если ничего не содержит) и занимает 100% ширины родительского элемента. Попробуем задать ему ширину в 200 пикселей и высоту в 150. Для этого используем CSS свойства width (ширина) и height (высота):

Можно задавать ширину не только в пикселях, но и в процентах от ширины родительского элемента. Попробуем сделать это:

К сожалению, задать высоту для блочного элемента в процентах не получится. Если написать «height:50%;», то в разных браузерах будет диаметрально противоположный результат, поэтому лучше считать такую запись ошибкой.

Только у одного элемента можно задать свойство height в процентах, а точнее у псевдоэлементов :before и ::after. Читайте о них в статье Псевдоэлементы (:before, ::after)

Максимальная и минимальная ширина (max-width и min-width)

Жёсткое ограничение ширины — это не лучший способ строить сайт. Потому что в таком случае появятся проблемы с адаптацией под мобильные и планшеты: ширина экрана может быть меньше ширины блока. Тогда часть сайта будет выходить пределы вёрстки сайта и появится горизонтальная прокрутка, чего у версии сайта на мобильном быть не должно. Поэтому вместо жёсткого задания ширины используется ограничение сверху через CSS свойство max-width. Мы знаем, что блочный элемент div пытается занять всю ширину родительского элемента, как будто по умолчанию у него есть свойство width и оно имеет значение 100%.

Но теперь, если вы возьмёте окно своего браузера и сузите до 400 пикселей и меньше, то увидите как контейнер div уменьшает свои размеры, чтобы не выпрыгивать за пределы вёрстки. Если же изменить «max-width:400px;» на «width:400px», то блок будет выходить за пределы родительского элемента:

По смыслу свойство min-width является диаметрально противоположным к max-width. Оно ограничивает минимальную ширину элемента, но не ограничивает максимальную.

Максимальная и минимальная высота (max-height и min-height)

Для блока div можно задать максимальную высоту. Это делается в том случае, если контента в блоке будет слишком много и есть вероятность, что он испортит вёрстку сайта. Ведь у контейнера div высота изменяется автоматически в зависимости от того, сколько занимает места его дочерние элементы.

Рассмотрим наглядный пример необходимости использования max-height. Допустим, что нам надо сделать чат, где пользователи сайта смогут обмениваться текстовыми сообщениями. Для этого нужно создать контейнер, который будет расти по мере появления в нём новых сообщений. Но как только div достигает определённой высоты, то перестаёт расти и появится полоса прокрутки. Используем следующий CSS код:

 
Тише, мыши, кот на крыше, а котята ещё выше. Кот пошёл за молоком, а котята кувырком. Кот пришёл без молока, а котята ха-ха-ха.

Весь текст не вместится в div. Поэтому из-за свойства «overflow-y: scroll;» появится полоса прокрутки:

Тише, мыши, кот на крыше, а котята ещё выше. Кот пошёл за молоком, а котята кувырком. Кот пришёл без молока, а котята ха-ха-ха.

Благодаря атрибуту contenteditable=»true» у тега div в примере, Вы можете изменить текст внутри контейнера. Попробуйте удалить и добавить несколько строк. Размер контейнера будет подстраиваться под количества текста в нём до тех пор, пока не станет быть равен 100px. Затем появится полоса прокрутки.

По смыслу свойство min-height является диаметрально противоположным к max-height. Оно ограничивает минимальную высоту элемента, но не ограничивает максимальную.

Источник

Оцените статью