Css блоки: Основы CSS: блочная модель – Блоки в CSS. Основы CSS для начинающих. Урок №13

Блоки в CSS — Изучение веб-разработки

Everything in CSS has a box around it, and understanding these boxes is key to being able to create layouts with CSS, or to align items with other items. In this lesson, we will take a proper look at the CSS Box Model so that you can build more complex layout tasks with an understanding of how it works and the terminology that relates to it.

Block and inline boxes

In CSS we broadly have two types of boxes — block boxes and inline boxes. These characteristics refer to how the box behaves in terms of page flow, and in relation to other boxes on the page:

If a box is defined as a block, it will behave in the following ways:

  • The box will extend in the inline direction to fill the space available in its container. In most cases this means that the box will become as wide as its container, filling up 100% of the space available.
  • The box will break onto a new line.
  • The width and 
    height
    properties are respected.
  • Padding, margin and border will cause other elements to be pushed away from the box

Unless we decide to change the display type to inline, elements such as headings (e.g. <h2>) and <p> all use block as their outer display type by default.

If a box has an outer display type of inline, then:

  • The box will not break onto a new line.
  • The width and height properties will not apply.
  • Padding, margin and borders will apply but will not cause other inline boxes to move away from the box.

The <a> element, used for links, <span>, <em> and <strong> are all examples of elements that will display inline by default.

The type of box applied to an element is defined by display property values such as

block and inline, and relates to the outer value of display.

Aside: Inner and outer display types

At this point, we’d better also explain inner and outer display types. As mentioned above, boxes in CSS have an outer display type, which details whether the box is block or inline.

Boxes also have an inner display type, however, which dictates how elements inside that box are laid out. By default, the elements inside a box are laid out in normal flow, which means that they behave just like any other block and inline elements (as explained above).

We can, however, change the inner display type by using display values like flex. If we set display: flex; on an element, the outer display type is block, but the inner display type is changed to flex. Any direct children of this box will become flex items and will be laid out according to the rules set out in the Flexbox spec, which you’ll learn about later on.

Note: To read more about the values of display, and how boxes work in block and inline layout, take a look at the MDN guide to Block and Inline Layout.

When you move on to learn about CSS Layout in more detail, you will encounter flex, and various other inner values that your boxes can have, for example grid.

Block and inline layout, however, is the default way that things on the web behave — as we said above, it is sometimes referred to as normal flow, because without any other instruction, our boxes lay out as block or inline boxes.

Examples of different display types

Let’s move on and have a look at some examples. Below we have three different HTML elements, all of which have an outer display type of block. The first is a paragraph, which has a border added in CSS. The browser renders this as a block box, so the paragraph begins on a new line, and expands to the full width available to it.

The second is a list, which is laid out using display: flex. This establishes flex layout for the items inside the container, however, the list itself is a block box and — like the paragraph — expands to the full container width and breaks onto a new line.

Below this, we have a block-level paragraph, inside which are two <span> elements. These elements would normally be inline, however, one of the elements has a class of block, and we have set it to display: block.

 

We can see how inline elements behave in this next example. The <span> elements in the first paragraph are inline by default and so do not force line breaks.

We also have a <ul> element which is set to display: inline-flex, creating an inline box around some flex items.

Finally, we have two paragraphs both set to

display: inline. The inline flex container and paragraphs all run together on one line rather than breaking onto new lines as they would do if they were displaying as block-level elements.

In the example, you can change display: inline to display: block or display: inline-flex to display: flex to toggle between these display modes.

 

You will encounter things like flex layout later in these lessons; the key thing to remember for now is that changing the value of the display property can change whether the outer display type of a box is block or inline, which changes the way it displays alongside other elements in the layout. 

In the rest of the lesson, we will concentrate on the outer display type.

What is the CSS box model?

The full CSS box model applies to block boxes, inline boxes only use some of the behavior defined in the box model. The model defines how the different parts of a box — margin, border, padding, and content — work together to create a box that you can see on the page. To add some additional complexity, there is a standard and an alternate box model.

Parts of a box

Making up a block box in CSS we have the:

  • Content box: The area where your content is displayed, which can be sized using properties like width and height.
  • Padding box: The padding sits around the content as white space; its size can be controlled using padding and related properties.
  • Border box: The border box wraps the content and any padding. Its size and style can be controlled using border and related properties.
  • Margin box: The margin is the outermost layer, wrapping the content, padding and border as whitespace between this box and other elements. Its size can be controlled using
    margin
    and related properties.

The below diagram shows these layers:

The standard CSS box model

In the standard box model, if you give a box a width and a height attribute, this defines the width and height of the content box. Any padding and border is then added to that width and height to get the total size taken up by the box. This is shown in the image below.

If we assume that the box has the following CSS defining width, height, margin, border, and padding:

.box {
  width: 350px;
  height: 150px;
  margin: 10px;
  padding: 25px;
  border: 5px solid black;
}

The space taken up by our box using the standard box model will actually be 410px (350 + 25 + 25 + 5 + 5), and the height 210px (150 + 25 + 25 + 5 + 5), as the padding and border are added to the width used for the content box.

Note: The margin is not counted towards the actual size of the box — sure, it affects the total space that the box will take up on the page, but only the space outside the box. The box’s area stops at the border — it does not extend into the margin.

The alternative CSS box model

You might think it is rather inconvenient to have to add up the border and padding to get the real size of the box, and you would be right! For this reason, CSS had an alternative box model introduced some time after the standard box model. Using this model, any width is the width of the visible box on the page, therefore the content area width is that width minus the width for the padding and border. The same CSS as used above would give the below result (width = 350px, height = 150px).

By default, browsers use the standard box model. If you want to turn on the alternative model for an element you do so by setting box-sizing: border-box on it. By doing this you are telling the browser to take the border box as the area defined by any size you set.

.box { 
  box-sizing: border-box; 
} 

If you want all of your elements to use the alternative box model, and this is a common choice among developers, set the box-sizing property on the <html> element, then set all other elements to inherit that value, as seen in the snippet below. If you want to understand the thinking behind this, see the CSS Tricks article on box-sizing.

html {
  box-sizing: border-box;
}
*, *::before, *::after {
  box-sizing: inherit;
}

Note: An interesting bit of history — Internet Explorer used to default to the alternative box model, with no mechanism available to switch.

Playing with box models

In the below example, you can see two boxes. Both have a class of .box, which gives them the same width, height, margin, border

, and padding. The only difference is that the second box has been set to use the alternative box model.

Can you change the size of the second box (by adding CSS to the .alternate class) to make it match the first box in width and height?

 

Note: You can find a solution for this task here.

Use browser DevTools to view the box model

Your browser developer tools can make understanding the box model far easier. If you inspect an element in Firefox’s DevTools, you can see the size of the element plus its margin, padding, and border. Inspecting an element in this way is a great way to find out if your box is really the size you think it is!

Margins, padding, and borders

You’ve already seen the margin, padding, and border properties at work in the example above. The properties used in that example are shorthands and allow us to set all four sides of the box at once. These shorthands also have equivalent longhand properties, which allow control over the different sides of the box individually.

Let’s explore these properties in more detail.

Margin

The margin is an invisible space around your box. It pushes other elements away from the box. Margins can have positive or negative values. Setting a negative margin on one side of your box can cause it to overlap other things on the page. Whether you are using the standard or alternative box model, the margin is always added after the size of the visible box has been calculated.

We can control all margins of an element at once using the margin property, or each side individually using the equivalent longhand properties:

In the example below, try changing the margin values to see how the box is pushed around due to the margin creating or removing space (if it is a negative margin) between this element and the containing element.

 

Margin collapsing

A key thing to understand about margins is the concept of margin collapsing. If you have two elements whose margins touch, and both margins are positive, those margins will combine to become one margin, which is the size of the largest individual margin. If one or both margins are negative, the amount of negative value will subtract from the total.

In the example below, we have two paragraphs. The top paragraph has a margin-bottom of 50 pixels. The second paragraph has a margin-top of 30 pixels. The margins have collapsed together so the actual margin between the boxes is 50 pixels and not the total of the two margins.

You can test this by setting the margin-top of paragraph two to 0. The visible margin between the two paragraphs will not change — it retains the 50 pixels set in the bottom-margin of paragraph one. If you set it to -10px, you’ll see that the overall margin becomes 40px — it subtracts from the 50px.

 

There are a number of rules that dictate when margins do and do not collapse. For further information see the detailed page on mastering margin collapsing. The main thing to remember for now is that margin collapsing is a thing that happens. If you are creating space with margins and don’t get the space you expect, this is probably what is happening.

Borders

The border is drawn between the margin and the padding of a box. If you are using the standard box model, the size of the border is added to the width and height of the box. If you are using the alternative box model then the size of the border makes the content box smaller as it takes up some of that available width and height.

For styling borders, there are a large number of properties — there are four borders, and each border has a style, width and color that we might want to manipulate.

You can set the width, style, or color of all four borders at once using the border property.

To set the properties of each side individually, you can use:

To set the width, style, or color of all sides, use the following:

To set the width, style, or color of a single side, you can use one of the most granular longhand properties:

In the example below we have used various shorthands and longhands to create borders. Have a play around with the different properties to check that you understand how they work. The MDN pages for the border properties give you information about the different styles of border you can choose from.

 

Padding

The padding sits between the border and the content area. Unlike margins you cannot have negative amounts of padding, so the value must be 0 or a positive value. Any background applied to your element will display behind the padding, and it is typically used to push the content away from the border.

We can control the padding on each side of an element individually using the padding property, or each side individually using the equivalent longhand properties:

If you change the values for padding on the class .box in the example below you can see that this changes where the text begins in relation to the box.

You can also change the padding on the class .container, which will make space between the container and the box. Padding can be changed on any element, and will make space between its border and whatever is inside the element.

 

The box model and inline boxes

All of the above applies fully to block boxes. Some of the properties can apply to inline boxes too, such as those created by a <span> element.

In the example below, we have a <span> inside a paragraph and have applied a width, height, margin, border, and padding to it. You can see that the width and height are ignored. The margin, padding, and border are respected but they do not change the relationship of other content to our inline box and so the padding and border overlaps other words in the paragraph.

 

Using display: inline-block

There is a special value of display, which provides a middle ground between inline and block. This is useful for situations where you do not want an item to break onto a new line, but do want it to respect width and height and avoid the overlapping seen above.

An element with display: inline-block does a subset of the block things we already know about:

  • The width and height properties are respected.
  • padding, margin, and border will cause other elements to be pushed away from the box.

It does not, however, break onto a new line, and will only become larger than its content if you explicitly add width and height properties.

In this next example, we have added display: inline-block to our <span> element. Try changing this to display: block or removing the line completely to see the difference in display models.

 

Where this can be useful is when you want to give a link to a larger hit area by adding padding. <a> is an inline element like <span>; you can use display: inline-block to allow padding to be set on it, making it easier for a user to click the link.

You see this fairly frequently in navigation bars. The navigation below is displayed in a row using flexbox and we have added padding to the <a> element as we want to be able to change the background-color when the <a> is hovered. The padding appears to overlap the border on the <ul> element. This is because the <a> is an inline element.

Add display: inline-block to the rule with the .links-list a selector, and you will see how it fixes this issue by causing the padding to be respected by other elements.

 

Summary

That’s most of what you need to understand about the box model. You may want to return to this lesson in the future if you ever find yourself confused about how big boxes are in your layout.

In the next lesson, we will take a look at how backgrounds and borders can be used to make your plain boxes look more interesting.

In this module

  1. Cascade and inheritance
  2. CSS selectors
  3. The box model
  4. Backgrounds and borders
  5. Handling different text directions
  6. Overflowing content
  7. Values and units
  8. Sizing items in CSS
  9. Images, media, and form elements
  10. Styling tables
  11. Debugging CSS
  12. Organizing your CSS

Блоки веб-страницы и их свойства — учебник CSS

Когда в браузере открывается веб-страница, он воспринимает ее теги в виде отдельных прямоугольных блоков (контейнеров), наполненных содержимым. У каждого такого элемента есть свой контент (текст, графика и прочее) и свои настройки CSS. Для блоков можно определять размеры, отступы, поля, рамки, фон, тем самым создавая для них стиль. Рассмотрим основные свойства CSS, устанавливаемые для блоков:

  • padding (и производные padding-left, padding-right, padding-top, padding-bottom) – это внутренний отступ от края содержимого до границы блока. Можно устанавливать отступы либо от всех четырех сторон контента, либо только от нужных вам.
  • margin (и производные margin-left, margin-right, margin-top, margin-bottom) – это поле, которое являет собой расстояние от границы одного блока до другого. Новички иногда путают свойство margin со свойством padding, поэтому для наглядности ниже показаны рисунки, где лучше понятна разница между этими свойствами. Поля можно задавать как для всех сторон блока одновременно, так и для отдельных.
  • border (и производные border-left, border-right, border-top, border-bottom) – это рамка (граница), которую можно задать для блока. Поля margin остаются за пределами рамки, всё остальное находится внутри неё. Рамку можно установить на всех четырех сторонах или только на нужных вам.
  • background-color – это цвет фона, заливка цветом, которая применяется к заднему фону блока и не выходит за его пределы. Поля этим цветом не закрашиваются, а контент и рамка располагаются поверх фона.
Схематическое изображение блока

Схематическое изображение блока


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

width + padding-left + border-left + margin-left + padding-right + border-right + margin-right = полная ширина блока

Аналогично вычисляется полная высота блока.

Ниже добавлен скриншот с пометками для лучшего понимания структуры блока:

Отступы, рамки и поля в блоке веб-страницы

Отступы, рамки и поля в блоке веб-страницы


В следующих разделах этой главы все вышеперечисленные свойства будут рассмотрены более подробно.

Далее в учебнике: поля и отступы CSS.

display: inline-block CSS блоки — уроки для начинающих академия



Дисплей: встроенный-блок значение

По сравнению с display: inline, основным отличием является то, что display: inline-block позволяет задавать ширину и высоту элемента.

Кроме того, с display: inline-block , верхний и нижний поля/обивка уважают, но с display: inline они не являются.

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

В следующем примере демонстрируется разное поведение display: inline, display: inline-block и display: block:

Пример

span.a {
    display: inline; /* the default for span */
    width: 70px;
    height: 70px;
    padding: 15px;
    border: 1px solid blue;
    background-color: yellow;
}

span.b {
    display: inline-block;
    width: 70px;
    height: 70px;
    padding: 15px;
    border: 1px solid blue;
    background-color: yellow;
}

span.c {
    display: block;
    width: 70px;
    height: 70px;
    padding: 15px;
    border: 1px solid blue;
    background-color: yellow;
}


Используйте встроенный блок для создания навигационных ссылок

Одним из распространенных применений display: inline-block является создание горизонтальных навигационных ссылок:

Пример

.nav {
    background-color: yellow;
    padding: 15px;
    list-style-type: none;
    text-align: center;   
}

.nav li {
    display: inline-block;
    font-size: 20px;
    padding-left: 20px;
    padding-right: 20px;
}


Сетка коробок

Было возможно в течение длительного времени, чтобы создать сетку коробок, который заполняет ширину браузера и обертывания красиво (при изменении размера обозревателя), с помощью свойства float .

Тем не менее, inline-block значение сво

Управление блочной моделью CSS

Управление блочной моделью CSS

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

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

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

Управление блочной моделью CSS

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

Управление блочной моделью CSS

Практический курс по верстке адаптивного сайта с нуля!

Изучите курс и узнайте, как верстать современные сайты на HTML5 и CSS3

Узнать подробнее

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

Управление блочной моделью CSS

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

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

Управление блочной моделью CSS

Рисунок 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, уменьшая размер контентной области. Многие программисты считают такой подход более разумным, несмотря на то, что он работает не по спецификации.

Управление блочной моделью CSS

Рисунок 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 на паддинге и рамке:

<div> <article> <h3>This is a headline</h3> <p>Lorem ipsum dolor sit amet, consectetur adipisicing … </p> </article> <aside> <h3>This is a secondary headline</h3> <p>Lorem ipsum dolor sit amet, consectetur adipisicing … </p> </aside> </div>

<div>

    <article>

    <h3>This is a headline</h3>

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

    </article>

    <aside>

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

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

    </aside>

</div>

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

Управление блочной моделью CSS

Практический курс по верстке адаптивного сайта с нуля!

Изучите курс и узнайте, как верстать современные сайты на HTML5 и CSS3

Узнать подробнее

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%;

}

Управление блочной моделью CSS

Рисунок 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 теперь применяется к внешней грани рамки, а не к контентной области, поэтому наши элементы плотно прижаты друг к другу и не сместились на новую строку.

Управление блочной моделью CSS

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

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

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

html { box-sizing: border-box; } *, *:before, *:after { box-sizing: inherit; }

html {

    box-sizing: border-box;

}

 

*, *:before, *:after {

    box-sizing: inherit;

}

Код выше применяет border-box ко всем тегам по умолчанию, не изменяя поведения box-sizing в существующих частях вашего проекта. Если вы точно знаете, что у вас не будет сторонних или старых компонентов, которые полагаются на content-box, то эти правила можно упростить:

*, *:before, *:after { box-sizing: border-box; }

*,

*:before,

*:after {

    box-sizing: border-box;

}

В таблице 4.1 представлена текущая поддержка в браузерах свойства box-size: border-box

Управление блочной моделью CSS

Управление блоковой моделью – это лишь один ингредиент в понимании того, как создавать сложные макеты. В следующем разделе мы с вами разберем слоистые элементы.

Автор: Tiffany Brown

Источник: https://www.sitepoint.com/

Редакция: Команда webformyself.

Управление блочной моделью CSS

Практический курс по верстке адаптивного сайта с нуля!

Изучите курс и узнайте, как верстать современные сайты на HTML5 и CSS3

Узнать подробнее Управление блочной моделью CSS

PSD to HTML

Практика верстки сайта на CSS Grid с нуля

Смотреть

Добавить комментарий

Ваш адрес email не будет опубликован. Обязательные поля помечены *