Box model css padding

CSS box model

The CSS box model module defines the rectangular boxes, including their padding and margin, that are generated for elements and laid out according to the visual formatting model.

Box model overview

A box in CSS consists of a content area, which is where any text, images, or other HTML elements are displayed. This is optionally surrounded by padding, a border, and a margin, on one or more sides. The box model describes how these elements work together to create a box as displayed by CSS. To learn more about it read Introduction to the CSS box model.

Box-edge keywords

The Box Model specification defines a set of keywords that refer to the edges of each part of the box, these are used as keyword values in CSS including as a value for the box-sizing property, to control how the box model calculates its size.

The edge of the content area of the box.

The edge of the padding of the box, if there is no padding on a side then this is the same as content-box .

The edge of the border of the box, if there is no border on a side then this is the same as padding-box .

Читайте также:  Css font with black border

The edge of the margin of the box, if there is no margin on a side then this is the same as border-box .

In SVG refers to the stroke bounding box, in CSS treated as content-box .

In SVG refers to the nearest SVG viewport element’s origin box, which is a rectangle with the width and height of the initial SVG user coordinate system established by the viewBox attribute for that element. In CSS treated as border-box .

Reference

Note: This specification defines the physical padding and margin properties. Flow-relative properties, which relate to text direction, are defined in Logical Properties and Values.

Properties for controlling the margin of a box

Margins surround the border edge of a box, and provide spacing between boxes.

Properties for controlling the padding for a box

Padding is inserted between the content edge and border edge of a box.

Other properties

There are other properties that relate to the box model, that are defined elsewhere.

The border properties specify the thickness of the border, drawing style and color.

Controls what happens when there is too much content to fit into a box.

Guides

Explains one of the fundamental concept of CSS: the box model. This model defines how CSS lays out elements, including their content, padding, border, and margin areas.

Sometimes, two adjacent margins are collapsed into one. This article describes the rules that govern when and why this happens, and how to control it.

Explains the visual formatting model.

Specifications

Found a content problem with this page?

This page was last modified on Jul 17, 2023 by MDN contributors.

Your blueprint for a better internet.

Источник

Блочная модель

Браузеры рисуют любой элемент на HTML-странице как прямоугольник. Как рассчитывается размер этого прямоугольника? Разберёмся с одной из основных концепций вёрстки.

Время чтения: меньше 5 мин

Обновлено 20 декабря 2021

«Всё — прямоугольник»

Скопировать ссылку ««Всё — прямоугольник»» Скопировано

Каждый элемент на веб-странице — это прямоугольник, к которому во время отрисовки браузеры применяют CSS-свойства. Чтобы конечные размеры элементов не были для вас сюрпризом и вы точно понимали, из чего они складываются, нужно разобраться с одной из основных концепций вёрстки — блочной моделью.

Блочная модель

Скопировать ссылку «Блочная модель» Скопировано

Блочная модель, она же box model — это алгоритм расчёта размеров каждого отдельного элемента на странице, которым браузеры пользуются при отрисовке. Чтобы точно понимать, каким в итоге получится блок и сколько места он займёт, держите в голове следующую картинку:

Схематичное изображение блочной модели

Ровно такую же схему, но в других цветах можно увидеть в инструментах разработчика любого из браузеров. Например, так выглядит блочная модель элемента в Chrome:

Скриншот блочной модели из инструментов разработчика браузера Chrome

Блочная модель состоит из нескольких CSS-свойств, влияющих на размеры элемента:

  • width — ширина элемента;
  • height — высота элемента;
  • padding — внутренние отступы от контента до краёв элемента;
  • border — рамка, идущая по краю элемента;
  • margin — внешние отступы вокруг элемента.

Ширина и высота

Скопировать ссылку «Ширина и высота» Скопировано

При помощи свойств width и height можно задавать размеры контентной области блока.

Контентной областью называется условное внутреннее пространство блока, где располагается контент. В примере ниже мы создаём блок при помощи тега , а внутрь вкладываем контент — текст:

   Вместе весело шагать по просторам!  div> Вместе весело шагать по просторам! div>      

По умолчанию элементы с блочным отображением ( display : block ) занимают всю ширину родителя, если явно не задано другое. А вот высота элемента подстраивается под контент.

Элементы со строчным ( display : inline ) или строчно-блочным ( display : inline — block ) отображениями по умолчанию подстраивают и ширину, и высоту под вложенный контент. Однако строчно-блочному можно и произвольно задать размеры: ширину ( width ) и высоту ( height ).

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

 div  width: 200px; height: 200px;> div  width: 200px; height: 200px; >      

Теперь элемент будет размером 200 на 200 пикселей.

padding

Скопировать ссылку «padding» Скопировано

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

Добавим к стилям из примера выше внутренние отступы:

 div  width: 200px; height: 200px; padding: 25px 15px;> div  width: 200px; height: 200px; padding: 25px 15px; >      

Теперь ширина блока будет равна 200 + 15 + 15 = 230 пикселей. А высота будет равна 200 + 25 + 25 = 250 пикселей. Внутренние отступы прибавились к ширине и высоте.

border

Скопировать ссылку «border» Скопировано

При определении размеров элемента в расчёт берутся и рамки, за которые отвечает свойство border .

Пусть у элемента из примера выше будет рамка со всех сторон:

 div  width: 200px; height: 200px; padding: 25px 15px; border: 5px solid hotpink;> div  width: 200px; height: 200px; padding: 25px 15px; border: 5px solid hotpink; >      

Теперь конечные размеры элемента будут:

margin

Скопировать ссылку «margin» Скопировано

Внешние отступы, за которые отвечает свойство margin , не прибавляются непосредственно к размерам элемента, но влияют на то, сколько места на странице он занимает.

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

 div  width: 200px; height: 200px; margin: 50px; padding: 25px 15px; border: 5px solid hotpink;> div  width: 200px; height: 200px; margin: 50px; padding: 25px 15px; border: 5px solid hotpink; >      

box — sizing

Скопировать ссылку «box-sizing» Скопировано

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

Мы можем поменять стандартное поведение и указать браузеру, что ширина и высота, заданные в CSS, должны включать в себя в том числе внутренние отступы и рамки. Делается это при помощи свойства box — sizing .

Источник

CSS Box Model

In CSS, the term «box model» is used when talking about design and layout.

The CSS box model is essentially a box that wraps around every HTML element. It consists of: margins, borders, padding, and the actual content. The image below illustrates the box model:

Explanation of the different parts:

  • Content — The content of the box, where text and images appear
  • Padding — Clears an area around the content. The padding is transparent
  • Border — A border that goes around the padding and content
  • Margin — Clears an area outside the border. The margin is transparent

The box model allows us to add a border around elements, and to define space between elements.

Example

Demonstration of the box model:

Width and Height of an Element

In order to set the width and height of an element correctly in all browsers, you need to know how the box model works.

Important: When you set the width and height properties of an element with CSS, you just set the width and height of the content area. To calculate the full size of an element, you must also add padding, borders and margins.

Example

This element will have a total width of 350px:

320px (width)
+ 20px (left + right padding)
+ 10px (left + right border)
+ 0px (left + right margin)
= 350px

The total width of an element should be calculated like this:

Total element width = width + left padding + right padding + left border + right border + left margin + right margin

The total height of an element should be calculated like this:

Total element height = height + top padding + bottom padding + top border + bottom border + top margin + bottom margin

Источник

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