Единицы измерения

CSS: как задавать размеры элементов на сайте

Мы тут рассказывали про размеры текста в вёрстке. Но что, если задавать размеры не только текста, но вообще всего? В CSS это делается так же легко, как и в случае с текстом.

Как задаются размеры

У большинства элементов в CSS есть такие параметры для работы с размером:

height, width — высота и ширина;

max-height, max-width — высота и ширина, больше которых элемент не может быть (а меньше — может);

min-height, min-width — минимальная высота и ширина;

margin — размер поля вокруг элемента. Другие элементы не должны влезать в это поле;

padding — отступы внутри элемента, например, если внутри будет написан текст.

Например, нам нужно нарисовать кнопку, внутри которой будет текст. Описание стиля кнопки может быть таким:

.button width:75%;
max-width:600px;
min-width:300px;
padding: 15px 15px 19px 15px;
margin: 20px auto 50px auto;
>

Перевод: кнопка должна занимать от 300 до 600 пикселей в ширину, а в этом диапазоне быть 75% ширины от содержащего ее контейнера; внутри кнопки отступи сверху 15 пикселей, справа 15, снизу 19, слева 15 (по часовой стрелке). Саму кнопку от ближайшего элемента сверху отодвинь на 20 пикселей, слева и справа отодвинь одинаково, чтобы она встала по центру, а снизу отступи еще 50 пикселей до следующего элемента.

Запись в стиле padding: 15px 15px 19px 15px — это короткий способ задать отступы по часовой стрелке. Первое значение — отступ сверху, второе — справа, третье — снизу, четвёртое — слева. Вместо короткой записи можно ещё так:

Но так обычно не пишут, потому что много текста.

Размеры в пикселях — жёстко, но точно

Самый простой способ задать размер элемента — указать его в пикселях. Например, если нам нужна ширина элемента 100 пикселей, то можно написать:

В пикселях можно задавать размеры почти чему угодно, потому что пиксели есть везде:

  • HTML-вёрстка предполагает, что содержимое будет отображаться на каком-то экране;
  • у каждого экрана, даже у виртуального, есть размер в пикселях по высоте и ширине экрана;
  • получается, браузер всегда сможет понять, сколько пикселей какую часть экрана занимают, и от этого он нарисует элемент нужного нам размера.

С пикселями есть только одна проблема: так как размеры и плотность пикселей на разных экранах разные, то может получиться так:

  • на экране 5-дюймового телефона с разрешением 1920 на 1080 пикселей баннер шириной 200 пикселей получит размер в 5 сантиметров;
  • а на мониторе с диагональю 24 дюйма, но с тем же разрешением 1920 на 1080 те же 200 пикселей будут иметь длину 10 сантиметров.

Чтобы было нагляднее, сделаем тестовую страницу с тремя блоками одинаковой высоты, но с шириной 100 пикселей.

div < /* у блоков будет единая высота */ height: 100px; /* и становиться они будут друг за другом в один ряд */ float: left; >/* у блоков будет одинаковая ширина, но разный цвет фона */ .div1 < width: 100px; background: red; >.div2 < width: 100px; background: green; >.div3

CSS: как задавать размеры элементов на сайте

CSS: как задавать размеры элементов на сайте

Справедливости ради, браузеры понимают эту проблему, поэтому умеют пересчитывать пиксели так, чтобы сайты не ломались. Например, если у вас есть современный экран с разрешением 288 точек на дюйм и тут же рядом старый экран с разрешением 72 точки на дюйм, то браузер поймёт, что надо пересчитать одни пиксели в другие. Если поставить два сайта рядом на этих экранах, они будут не один в один, но похожи.

Читайте также:  No such file or directory css

Получите ИТ-профессию Получите ИТ-профессию Получите ИТ-профессию Получите ИТ-профессию

В зависимости от размеров экрана — гибко, но надо перепроверять на разных экранах

Чтобы не зависеть от размера пикселей, а масштабировать элементы в зависимости от размера экрана, придумали другие единицы измерения:

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

В этом случае браузер сделает так:

  1. Посмотрит, что за единица измерения — vw, значит нужна ширина экрана.
  2. Узнает, какой ширины в пикселях окно, в котором открывается эта страница.
  3. Поделит её на 100, чтобы узнать размер одного vw в пикселях.
  4. Умножит это значиние на 50, чтобы понять размер в пикселях нужного нам элемента.
  5. Установит это значение в пикселях при вёрстке.
  6. Если в процессе просмотра у браузера поменяется размер экрана — он сам всё пересчитает и отрисует заново.

Используем страницу из предыдущего раздела и немного переделаем её — установим такой размер блоков:

div < /* у блоков будет единая высота */ height: 100px; /* и становиться они будут друг за другом в один ряд */ float: left; >/* задаём ширину относительно ширины экрана */ .div1 < width: 10vw; background: red; >.div2 < width: 20vw; background: green; >.div3

Если нам нужно, чтобы блоки по высоте занимали всю высоту экрана, то для этого достаточно указать в стилях div такой параметр:

CSS: как задавать размеры элементов на сайте

Ещё есть vmin и vmax, которые работают так:

  • vmin находит минимальное значение из пары (vh, vw);
  • а vmax находит максимальное значение из пары (vh, vw).

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

Проценты — очень гибко, но всегда нужен родительский элемент

Кажется, что vh и vw — это и есть те самые проценты от ширины экрана и что можно обойтись без обычных процентов. Но на самом деле просто проценты в вёрстке тоже используются, но с одним важным моментом:

👉 Чтобы использовать проценты, нужен родительский элемент, от которого эти проценты будут считаться.

Родительский элемент — тот, внутри которого находятся другие наши элементы. Например, мы хотим сделать на странице блок шириной 500 пикселей:

У этого блока есть точный размер, который браузер может взять или посчитать. Теперь внутри этого блока мы легко можем расположить свои блоки в тех же процентах, что и в предыдущем примере:

div < /* у блоков будет единая высота */ height: 100vh; /* и становиться они будут друг за другом в один ряд */ float: left; >/* задаём ширину в процентах относительно родителя */ .div1 < width: 10%; background: red; >.div2 < width: 20%; background: green; >.div3

CSS: как задавать размеры элементов на сайте

Если мы явно не указали размер родительского элемента, то браузер постарается угадать его или посчитать самостоятельно. Но получится это не всегда.

Нужно ли в этом разбираться?

Вообще в современном мире взрослые фронтендеры верстают с помощью css-grid и готовых верстальных фреймворков: в них все размеры стандартизированы и прописаны под капотом, а верстальщики просто говорят «большое», «среднее», «сбоку», «на три четверти», «на всю ширину» и т. д. А уже как это интерпретировать и какие конкретно там размеры — этим занимается фреймворк.

Источник

CSS Button Size

This article will go over the concept of the button size in the CSS style approach. As we know, the default button is small in size and is not visible. So, we will use the CSS in two separate ways to increase the button size and alter it on an effect like the hover effect. All these examples will be performed in the Notepad++ environment.

Читайте также:  Javascript проверить свойство объекта

Example 01:

In this example, we will use the width and height property for the button element to increase its size. We will use the CSS Style Tag approach in this example to add several properties. First, we will look at the default size of the button element present in an HTML file.

Text, application Description automatically generated with medium confidence

As we can see in the given script, we have not altered the size of the button. In the following output, we can see that the button size is very small and is not feasible for a web page.

Text Description automatically generated with medium confidence

So, now we add the styling to the button. First, we open the head tag for the file. In this tag, the style tag for CSS is called. In this tag, we add all the properties for the button element. We write all the properties for the button element inside the button class parenthesis. First, we set the background color to “yellow”. Then, we set the width in pixel format to “100px”. Finally, we set the height in pixel format to “30px”. We close the style and head tags after all of the formatting are complete. Then, we go to the body tag. We write the page’s headline using the h1 tag in the body tag and then open the button tag. The class from the style tag is called in the button tag. Following that, we close the button tag with the text that displays on the button in between, as well as the body tag.

Text, letter Description automatically generated

As explained earlier, we added the code in the previous script. Now, we open this new script on our browser after saving it in the correct format.

A picture containing graphical user interface Description automatically generated

In the given output, we can see that the button has all the formatting including the size that we specified in the style class in the file header.

Example 02: Using Inline CSS to Alter the Size of a Button in an HTML File

In this example, we will use the inline CSS to change the size of an HTML file’s default button element. All the style properties will be assigned inside the button tag. This is an unconventional method to add CSS to any element and will only be associated with the current element.

Text Description automatically generated

As we can see in the previous snippet, we directly moved to the body of the file as all the content would be in the body tag. First, we open the h1 tag to write a heading for the page and then close it. Then, we open the button tag. In this tag, we call the style attribute by its keyword. After this, we write all the properties for the button element in the inverted commas and separate them by using the semicolon character. First, we assign the background color, “yellow”. Then, we assign the width in the pixel format. In the end, we assign the height, also in the pixel format. After this, we close the button tag with the text in between, which will appear on the button. And close the body tag along with it. Now, we save this file in the “.html” format and open it on our browser to get the following result:

Graphical user interface Description automatically generated with low confidence

As we can see in the output of our script, the heading and button from the body tag are visible. The button has all of the values defined in the tag, including the height and width.

Читайте также:  Ansible raw install python

Example 03: Increasing the Size of a Button When It Hovers With Our Cursor in an HTML File

In this example, we will use the width and height properties of the button element to make it bigger, only when the pointer is over it. In this example, we will use the CSS style tags to add numerous attributes and effects to the button element.

Text, letter, timeline Description automatically generated

In this example, we customize the button using the CSS style tags. First, we open the file’s head tag. And then, we call the CSS style tag from there. We add all of the button element’s attributes in this tag. Inside the button class parenthesis, we enter all of the properties for the button element; in this example, we set the background color to “yellow.” Then, we open a button class that inherits a method called “hover”. In this function, we do the following: we set the width in pixel format to “100px” and set the height in pixel format to “30px”. After we finish formatting, we close the style and head tags. Then, we go to the body tag. We use the h1 tag to create the page’s title in the body tag, then open the button tag. The button tag uses the class from the style tag and have the text that appears on the button in between. Following that, we close the button tag and the body tag.

Graphical user interface Description automatically generated with low confidence

As we can see in the previous output, the size and the background color have changed as we hovered on the button with our cursor. This is because the hover function has all these properties defined in the style tag of the header’s file.

Example 04: Using the Font Size to Enhance the Size of a Button Using CSS

In this example, we will opt to a different method to change the size of a button. The font size property will be used to increase the size of a button using the style tag CSS.

Text Description automatically generated

First, we open the style tag in the file header and create a styling class for the button. In this class, we assign a background color to the button. After that, we assign the font size as well. In this case, it is set to “25px”. Then, we close the class and the style and head tags, respectively. Then the body tag has a heading and a button tag which have the style tag class inherited in it. After this, we close the tags and save the file to open it on our browser.

A picture containing graphical user interface Description automatically generated

In the output screen, we can see that the button has an increased size from the default button that the HTML provides due to the change in the font size property.

Conclusion

In this article, we discussed the size of the button element present in the Hypertext Markup Language. The default button has a very small size which makes it difficult to navigate on a web page. So, we used the different approaches in CSS like the style tag and inline CSS approach. The most common property used to alter the size are the width and height property of a button. We discussed this concept and implemented this on the Notepad++. We also implemented the font size approach to increase the size of a button.

About the author

Aqsa Yasin

I am a self-motivated information technology professional with a passion for writing. I am a technical writer and love to write for all Linux flavors and Windows.

Источник

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