Блочная модель документа второе испытание 16 23. Определение реальных размеров элементов

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

Создается бокс или нет, а также тип этого бокса зависит от языка разметки. CSS спроектирован как способ стилизации HTML-документов, поэтому модель визуального рендеринга CSS в значительной степени корениться в различиях между блочными и инлайновыми элементами в HTML. По умолчанию элементы p и section создают боксы блочного уровня, а теги a, span и em создают инлайновые боксы. SVG вообще не использует блоковую модель, поэтому большая часть макетных свойств CSS не работает с SVG.

Боксы блочного уровня создают новые блоки контента, как видно на Рисунке 4.1. Блочные боксы рендерятся вертикально в исходном порядке и заполняют (кроме таблиц) всю ширину контейнера. Это обычное отображение значений block, list-item, table и других table-* значений (например, table-cell).

Рисунок 4.1. боксы блочного уровня в тегах h1, p, ul и table внутри контейнера (серая область)

Боксы инлайнового уровня не формируют новые блоки контента. Эти боксы создают строки внутри блочного бокса. Они отображаются горизонтально и заполняют ширину бокса-контейнера, перепрыгивая на новые строки по необходимости, как показано на Рисунке 4.2. К боксам инлайнового уровня относятся значения свойства display inline, inline-block, inline-table и ruby.

Рисунок 4.2. пример инлайнового бокса с margin: 1em и padding: 5px

Но как же рассчитываются размеры бокса? Вот тут все немного сложнее. На Рисунке 4.3 видно, что размеры бокса складываются из контентной области, padding’а и ширины, плюс ширина рамки, как определено в CSS2. Ширина margin’а создает на элементе margin-бокс и влияет на другие элементы в документе, но никак не воздействует на размеры самого бокса.

Рисунок 4.3. блоковая модель по CSS 2.1

Например, тег p с width: 300px, padding: 20px и border: 10px будет иметь вычисленную ширину в 360px. Ширина складывается из ширины параграфа, левого и правого паддинга, а также из левого и правого border-width. Чтобы общая ширина элемента была 300px, при этом сохраняя 20px паддинга и 10 пикселей рамки, необходимо задать width: 240px. Большинство браузеров вычисляют ширину именно таким образом. Но это не относится к IE 5.5.

IE 5.5 использует свойство width, как окончательное значение для размеров бокса, загоняя паддинг и рамку внутрь бокса, как показано на Рисунке 4.4. Оба значения вычитаются из width, уменьшая размер контентной области. Многие программисты считают такой подход более разумным, несмотря на то, что он работает не по спецификации.

Рисунок 4.4 блоковая модель в CSS 2.1 и блоковая модель в старом IE 5.5

Рабочая группа CSS представила свойство box-sizing, как частичный способ решения этих конкурирующих моделей. Оно позволяет выбирать реализация блоковой модели, а также сильно упрощает вычисления при работе с адаптивным дизайном.

Выбор блоковой модели с помощью свойства box-sizing

Свойство box-sizing определено в спецификации CSS Basic User Interface Module Level 3 и принимает два возможных значения: content-box и border-box.

По умолчанию установлено значение content-box. С этим значением свойства width и height влияют на размер контентной области, что совпадает с поведением, описанным в спецификации CSS 2.1. Такое поведение установлено по умолчанию в современных браузерах (как показано на Рисунке 4.4).

Значение border-box добавляет немного магии. Свойства width и height начинают применяться к внешней границе рамки, а не к контентной области. Рамка и паддинг рисуются внутри бокса элемента, что совпадает со старым поведением в IE 5.5. Давайте разберем пример, в котором ширина в процентах совмещена с px на паддинге и рамке:

This is a headline

< div class = "wrapper" >

< article >

< h2 > This is a headline < / h2 >

< p >< / p >

< / article >

< aside >

< h2 > This is a secondary headline < / h2 >

< p > Lorem ipsum dolor sit amet , consectetur adipisicing . . . < / p >

< / aside >

< / div >

К тегам article и aside применен CSS-код ниже, что дает нам макет, показанный на Рисунке 4.5, где первый элемент имеет ширину 60%, а второй – 40%:

article, aside { background: #FFEB3B; border: 10px solid #9C27B0; float: left; padding: 10px; } article { width: 60%; } aside { width: 40%; }

article , aside {

background : #FFEB3B;

border : 10px solid #9C27B0;

float : left ;

padding : 10px ;

article {

width : 60 % ;

aside {

width : 40 % ;

Рисунок 4.5. элементы с box-sizing: content-box

По умолчанию aside и article задано свойство box-sizing со значением content-box. Значения border-width и padding добавляют 40 пикселей к ширине элементов, что изменяет соотношение 60%/40%. Давайте добавим к тегам article и aside свойство box-sizing: border-box:

article, aside { box-sizing: border-box; }

article , aside {

box - sizing : border - box ;

Изменения показаны на Рисунке 4.6: ширина элементов сохранилась, однако из-за box-sizing: border-box ширина теперь состоит также из рамки и паддинга. Width теперь применяется к внешней грани рамки, а не к контентной области, поэтому наши элементы плотно прижаты друг к другу и не сместились на новую строку.

Рисунок 4.6 элементы с box-sizing: border-box

Я предложил бы использовать свойство box-sizing: border-box. Оно упрощает жизнь, с ним не нужно вычислять width, чтобы подогнать ширину под padding и border.

Лучше всего применять box-sizing: border-box с правилами сброса. Пример ниже взят из статьи Криса Койера с CSS-Tricks «

The CSS box model is the foundation of layout on the Web - each element is represented as a rectangular box, with the box"s content, padding, border, and margin built up around one another like the layers of an onion. As a browser renders a web page layout, it works out what styles are applied to the content of each box, how big the surrounding onion layers are, and where the boxes sit in relation to one another. Before understanding how to create CSS layouts, you need to understand the box model - this is what we"ll look at in this article.

Prerequisites: Basic computer literacy, basic knowledge of , HTML basics (study Introduction to HTML), and an idea of How CSS works (study the previous articles in this module .)
Objective: To learn how the CSS box model works, and how individual elements are laid out on a page.

Box properties

Every element within a document is structured as a rectangular box inside the document layout, the size and "onion layers" of which can be tweaked using some specific CSS properties. The relevant properties are as follows:

Note : Margins have a specific behavior called margin collapsing : When two boxes touch against one another, the distance between them is the value of the largest of the two touching margins, and not their sum.

Active learning: playing with boxes

At this point, let"s jump into an active learning section and carry out some exercises to illustrate some of the particulars of the box model that we discussed above. You can try these exercises in the live editor below, but it might be easier to see some of the effects if you create separate HTML and CSS files locally and try it in a separate browser window instead. You can find the example code on Github .

If you make a mistake, you can always reset it using the Reset button. If you get really stuck, press the Show solution button to see a potential answer.

In the editable sample below, we have a set of three boxes, all of which contain text content and have been styled to span the whole of the body width. They are represented by element represents introductory content, typically a group of introductory or navigational aids. It may contain some heading elements but also other elements like a logo, a search form, an author name, and so on.">

, of a document. The main content area consists of content that is directly related to or expands upon the central topic of a document, or the central functionality of an application.">
, and element represents a footer for its nearest sectioning content or sectioning root element. A footer typically contains information about the author of the section, copyright data or links to related documents.">
elements in the markup. We"d like you to concentrate on the bottom three CSS rules - the ones that target each box individually - and try the following:

  • Have a look at the box model of each individual element on the page by opening up the browser developer tools and clicking on the elements in the DOM inspector. See Discover browser developer tools for help on how to do this. Each browser has a box model viewer that shows exactly what margin, border and padding is applied to each box, how big the content box is, and the total space the element takes up.
  • Set some margin-bottom on the element represents the dominant content of the of a document. The main content area consists of content that is directly related to or expands upon the central topic of a document, or the central functionality of an application.">
    element, say 20px. Now set some margin-top on the element represents a footer for its nearest sectioning content or sectioning root element. A footer typically contains information about the author of the section, copyright data or links to related documents.">
    element, say 15px. Note how the 2nd one of these actions makes no difference to the layout - this shows in action; the smaller margin"s effective width is reduced to 0, leaving only the larger margin.
  • Set a margin of 30px and a padding of 30px on every side of the element represents the dominant content of the of a document. The main content area consists of content that is directly related to or expands upon the central topic of a document, or the central functionality of an application.">
    element - note how the space around the element (the margin) and the space between the border and the content (the padding) both increase, causing the actual content to take up a smaller amount of space. Again, check this with the browser developer tools.
  • Set a larger border on all sides of the element represents the dominant content of the of a document. The main content area consists of content that is directly related to or expands upon the central topic of a document, or the central functionality of an application.">
    element, say 40px, and notice how this takes space away from the content rather than the margin or padding. You could do this by setting a complete new set of values for the width, style and color with the border property, e.g. 60px dashed red , but since the properties are already set in a previous rule, you could just set a new border-width .
  • By default, the content width is set to 100% of the available space (after the margin, border, and padding have taken their share) - if you change the browser window width, the boxes will grow and shrink to stay contained inside the example output window. The height of the content will default to the height of the content inside it.
  • Try setting a new width and height on the element represents the dominant content of the of a document. The main content area consists of content that is directly related to or expands upon the central topic of a document, or the central functionality of an application.">
    element - start with say 400px width and 200px height - and observe the effect. You"ll notice that the width no longer changes as the browser window is resized.
  • Try setting a percentage width on the element represents the dominant content of the of a document. The main content area consists of content that is directly related to or expands upon the central topic of a document, or the central functionality of an application.">
    element instead - say 60% width - and observe the effect. You should see that the width now changes again as the browser window is resized. Remove the element represents the dominant content of the of a document. The main content area consists of content that is directly related to or expands upon the central topic of a document, or the central functionality of an application.">
    element"s height setting for now.
  • Try setting your element represents the dominant content of the of a document. The main content area consists of content that is directly related to or expands upon the central topic of a document, or the central functionality of an application.">
    element"s padding and margin to be 5% on all sides, and observe the result. If you use your browser developer tools to look at the width of the example output window and compare that to the width of the margin/padding, you"ll see that this 5% means "5% of the containing element"s width." So as the size of the example output window increases, so does the padding/margins.
  • Margins can accept negative values, which can be used to cause element boxes to overlap. Try setting margin-top: -50px; on the element represents the dominant content of the of a document. The main content area consists of content that is directly related to or expands upon the central topic of a document, or the central functionality of an application.">
    element to see the effect.
  • Keep experimenting!
Playable code

HTML Input

CSS Input

Output

var htmlInput = document.querySelector(".html-input"); var cssInput = document.querySelector(".css-input"); var reset = document.getElementById("reset"); var htmlCode = htmlInput.value; var cssCode = cssInput.value; var output = document.querySelector(".output"); var solution = document.getElementById("solution"); var styleElem = document.createElement("style"); var headElem = document.querySelector("head"); headElem.appendChild(styleElem); function drawOutput() { output.innerHTML = htmlInput.value; styleElem.textContent = cssInput.value; } reset.addEventListener("click", function() { htmlInput.value = htmlCode; cssInput.value = cssCode; drawOutput(); }); solution.addEventListener("click", function() { htmlInput.value = htmlCode; cssInput.value = "/* General styles */\n\nbody {\n margin: 0;\n}\n\n#wrapper > * {\n padding: 20px;\n font-size: 20px;\n border: 20px solid rgba(0,0,0,0.5);\n}\n\n/* specific boxes */\n\n#wrapper header, #wrapper footer {\n background-color: blue;\n color: white;\n}\n\n#wrapper main {\n background-color: yellow;\n margin: 2%;\n padding: 2%;\n border: 60px solid rgba(0,0,0,0.5);\n width: 60%;\n}\n\n#wrapper header {\n\n}\n\n#wrapper footer {\n margin-top: 20px;\n}"; drawOutput(); }); htmlInput.addEventListener("input", drawOutput); cssInput.addEventListener("input", drawOutput); window.addEventListener("load", drawOutput);

Some hints and ideas:

Advanced box manipulation

Beyond setting the width, height, border, padding and margin of boxes, there are some other properties available to change how they behave. This section discusses those other properties.

Overflow

When you set the size of a box with absolute values (e.g. a fixed pixel width/height), the content may not fit within the allowed size, in which case the content overflows the box. To control what happens in such cases, we can use the overflow property. It takes several possible values, but the most common are:

  • auto: If there is too much content, the overflowing content is hidden and scroll bars are shown to let the user scroll to see all the content.
  • hidden: If there is too much content, the overflowing content is hidden.
  • visible: If there is too much content, the overflowing content is shown outside of the box (this is usually the default behavior.)

Here is a simple example to show how these settings work:

First, some HTML:

Lorem ipsum dolor sit amet, consectetur adipiscing elit. Mauris tempus turpis id ante mollis dignissim. Nam sed dolor non tortor lacinia lobortis id dapibus nunc. Praesent iaculis tincidunt augue. Integer efficitur sem eget risus cursus, ornare venenatis augue hendrerit. Praesent non elit metus. Morbi vel sodales ligula.

Lorem ipsum dolor sit amet, consectetur adipiscing elit. Mauris tempus turpis id ante mollis dignissim. Nam sed dolor non tortor lacinia lobortis id dapibus nunc. Praesent iaculis tincidunt augue. Integer efficitur sem eget risus cursus, ornare venenatis augue hendrerit. Praesent non elit metus. Morbi vel sodales ligula.

And now some CSS to apply to our HTML:

P { width: 400px; height: 2.5em; padding: 1em 1em 1em 1em; border: 1px solid black; } .autoscroll { overflow: auto; } .clipped { overflow: hidden; } .default { overflow: visible; }

The above code gives the following result:

Background clip

Box backgrounds are made up of colors and images, stacked on top of each other ( background-color , background-image .) They are applied to a box and drawn under that box. By default, backgrounds extend to the outer edge of the border. This is often fine, but in some cases it can be annoying (what if you have a tiled background image that you want to only extend to the edge of the content?) This behaviour can be adjusted by setting the or extends underneath its border."> background-clip property on the box.

Let"s have a look at an example, to see how this works. First, our HTML:

Div { width: 60px; height: 60px; border: 20px solid rgba(0, 0, 0, 0.5); padding: 20px; margin: 20px 0; background-size: 140px; background-position: center; background-image: url("https://mdn.mozillademos.org/files/11947/ff-logo.png"); background-color: gold; } .default { background-clip: border-box; } .padding-box { background-clip: padding-box; } .content-box { background-clip: content-box; }

The above code produces the following result:

Outline

See also

  • Block formatting context : The technical term for a CSS box laid out on a web page.
  • Visual formatting model : An in depth explanation of the algorithm that lays out CSS boxes on a web page.

Последнее обновление: 21.04.2016

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

Схематично блочную модель можно представить следующим образом:

Пусть элемент расположен в каком-нибудь внешнем контейнере. Это может быть элемент body, div и так далее. От других элементов он отделяется некоторым расстоянием - внешним отступом, которое описывается свойством CSS margin . То есть свойство margin определяет расстояние от границы текущего элемента до других соседних элементов или до границ внешнего контейнера.

После границы идет внутренний отступ, который в CSS описывается свойством padding . Внутренний отступ определяет расстояние от границы элемента до внутреннего содержимого.

Например, определим следующую веб-страницу:

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

Первый блок

Второй блок

После запуска веб-страницы в браузере мы можем посмотреть блочную модель конкретных элементов. Для этого надо нажать на нужный элемент правой кнопкой мыши и открывающемся контекстном меню выбрать пункт, который позволяет просмотреть исходный код элемента. Для разных браузеров этот пункт может называться по разному. К примеру в Google Chrome это Посмотреть код :

В Mozilla Firefox этот пункт называется Исследовать элемент .

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

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

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

Вся html страница состоит из блоков

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

margin

<html > <head > <title > Главная</ title > <meta http-equiv = "Content-Type" content = "text/html; charset=utf-8" > <link rel = "stylesheet" type = "text/css" href = "style.css" > </ head > <body > <div id = "content" > <div class = "firstPar" > <p > </ p > <p > </ p > </ div > <div class = "secondPar" > <p > Cras</ p > <ul > <li > amet condimentum</ li > <li > aliquam volutpat</ li > <li > elementum interdum</ li > </ ul > </ div > </ div > </ body > </ html >

А в CSS для каждого из блоков

пропишем разные границы:

Посмотрим как это выглядит в браузере:

Сейчас применим для блока

свойство margin — внешние отступы. Что касается данного свойство оно как и граница может быть: margin-top , margin-right , margin-bottom и margin-left . А отступы задаются в пикселях(px). Также данное свойство может наследоваться от родителя. Давайте попробуем сделать отступ:

Как это выглядит в браузере:


А сейчас попробуем поставить отступы сразу со всех сторон:

Как это выглядит в браузере:


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

Давайте подробно рассмотрим данную запись:

Как видите первая цифра отвечает за отступ сверху, вторая — отступ справа, третья — отступ снизу и четвертая — отступ слева.

padding

Отступы бывают внешними и внутренними. Как вы уже знаете внешние задаются через свойство margin . Внутренние отступы задаются с помощью свойства padding .

Для примера возьмем код из прошлого примера:

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 <html > <head > <title > Главная</ title > <meta http-equiv = "Content-Type" content = "text/html; charset=utf-8" > <link rel = "stylesheet" type = "text/css" href = "style.css" > </ head > <body > <div id = "content" > <div class = "firstPar" > <p > Aliquam malesuada tellus justo, eget lacinia nunc rutrum a. Phasellus dictum tempor eleifend. Nunc ut magna non purus fermentum egestas ac eu nulla.</ p > <p > Fusce est tellus, mattis quis nisl et, egestas posuere libero. Donec scelerisque tellus porttitor massa dictum pulvinar.</ p > </ div > <div class = "secondPar" > <p > Cras</ p > <ul > <li > amet condimentum</ li > <li > aliquam volutpat</ li > <li > elementum interdum</ li > </ ul > </ div > </ div > </ body > </ html >

И зададим для второго блока внутренний отступ в 20 пикселей(px).

В CSS существует, по большому счету, четыре способа раскладывать боксыпо странице: прямой поток, позиционирование, плавающие блоки, таблицы. Ни один из них не дает полного набора средств, которыми можно было бы сверстать что-нибудь реальное.

Суть позиционирования очень проста: любой бокс можно расположить в любом месте страницы, задав ему точные координаты. Именно любой, а не только <div >. Существуют четыре способа позиционирования боксов.

Статическое (Static ), отсутствие какого бы то ни было специального позиционирования, а просто выкладывание боксов одного за другим сверху вниз – прямой поток. Способ по умолчанию.

Абсолютное (Absolute ). Бокс с абсолютным позиционированием располагается по заданным координатам, а из того места, где он должен был бы быть, он удаляется, и в этом месте сразу начинают раскладываться следующие боксы. Говорят, что он "исключается из потока".

Фиксированное (Fixed ). Схоже сabsolute , но при этом он не скролится вместе с остальной страницей.

Относительное (Relative ). Такой бокс можно сдвинуть относительно того места, где он был бы в потоке, но при этом из потока он не исключается, а продолжает занимать там свое место. То есть сдвигается со своего места он только визуально, а положение всех боксов вокруг него никак не меняется.

Рисунок 5.2 – Способы позиционирования боксов

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

#somebox {

position:absolute;

left:100px; top:100px;

bottom :100 px ; right :100 px ;

Координаты означают расстояние бокса от краев содержащего блока. Любая из координат необязательна. В случае, если координаты не задают вертикального или горизонтального положения, то оно остается таким же, какое было бы без позиционирования. То есть в случае, когда у нас есть два произвольных бокса один за другим "box1" и "box2", то по вертикали он останется прямо под первым боксов, а по горизонтали будет отстоять от левого края на 150 пикселов:

< div id =" box 1"> первый div >

< div id =" box 2"> второй div >

и второй мы позиционируем так:

position:absolute;

left:150px;

Рассмотрим относительно каких границ двигают бокс координатные свойства.

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

Позиционированный бокс внутри себя, также создает такой же стакан, и все боксы, находящиеся у него внутри позиционируются уже относительно него, а не относительно окна.

Любой позиционированный (не static ) бокс создает внутри себя такой стакан в терминологии CSS называемый – содержащий блок (containing block ).

Бокс с position:fixed – это, разновидность того же абсолютного позиционирования с разницей в том, что при скролинге окна эти боксы остаются на месте. Этот эффект широко используется на страницах веб-приложений для всяческих прилипающих блоков меню и тулбаров. Особенность – если фиксированный бокс не влезет в окно, то доскролиться до него будет уже нельзя.

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

#somebox {

position:absolute;

top:0; left:0; right:0;

margin :20 px ; padding :20 px ;

Этот бокс с заданными левой и правой координатами будет точно касаться боковых сторон своего содержащего блока , какой бы ширины тот ни был, а margin"ы и padding"и будут откладываться внутрь бокса.

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

Рисунок 5.3 – Пример абсолютного позиционирования боксов

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

Пример - абсолютным позиционированием нельзя сделать самую традиционную раскладку: заголовок, содержимое любой высоты в несколько колонок и нижний блок. Обычно получается такое – рисунок 5.4

Рисунок 5.4 – Пример абсолютного позиционирования боксов

Видны две проблемы:

    Колонки не получается выровнять по высоте, потому что колонки друг в друге не лежат, и в CSS нет средств сказать "высота как вот у другого бокса.

    Нижний блок проваливается за колонки, потому что они изымаются из потока, и нижний блок по высоте не толкают. И его нельзя абсолютно позиционировать под самой высокой колонкой, потому что в CSS нет средств сказать "верх под тем другим боксом".

Относительное позиционирование похоже на абсолютное, но к нему зачем-то добавляется эффект: бокс продолжает занимать место в потоке.

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

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

Содержимое