Thuộc Tính Margin Và Padding Trong Css

     

Everything in CSS has a box around it, và understanding these boxes is key lớn being able khổng lồ create layouts with CSS, or khổng lồ 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 & the terminology that relates khổng lồ it.

Bạn đang xem: Thuộc tính margin và padding trong css

Prerequisites: Objective:
Basic computer literacy, basic software installed, basic knowledge of working with files, HTML basics (study Introduction to lớn HTML), và an idea of how CSS works (study CSS first steps.)
To learn about the CSS Box Model, what makes up the box mã sản phẩm and how khổng lồ switch to the alternate mã sản phẩm.

Blochồng & inline boxes


In CSS we broadly have sầu two types of boxes — blochồng boxes and inline boxes. These characteristics refer khổng lồ how the box behaves in terms of page flow, & in relation khổng lồ other boxes on the page:

If a box is defined as a blochồng, it will behave in the following ways:

The box will break onto a new line. The box will extover in the inline direction lớn 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. Padding, margin và border will cause other elements to lớn be pushed away from the box

Unless we decide lớn change the display type to inline, elements such as headings (e.g. ) and all use bloông chồng as their outer display type by mặc định.

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

The box will not break onto a new line. Vertical padding, margins, và borders will apply but will not cause other inline boxes lớn move away from the box. Horizontal padding, margins, và borders will apply and will cause other inline boxes khổng lồ move sầu away from the box.

The element, used for links, , are all examples of elements that will display inline by mặc định.

The type of box applied khổng lồ an element is defined by display property values such as bloông xã & inline, và relates to lớn the outer value of display.


Aside: Inner and outer display types


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

Boxes also have sầu an inner display type, however, which dictates how elements inside that box are laid out. By mặc định, the elements inside a box are laid out in normal flow, which means that they behave just lượt thích any other blochồng và 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 blochồng, but the inner display type is changed to flex. Any direct children of this box will become flex items và will be laid out according lớn the rules mix out in the Flexbox spec, which you"ll learn about later on.


Note: To read more about the values of display, & how boxes work in blochồng & inline layout, take a look at the MDN guide lớn Bloông xã & Inline Layout.


When you move on lớn learn about CSS Layout in more detail, you will encounter flex, và various other inner values that your boxes can have sầu, for example grid.

Bloông xã and inline layout, however, is the mặc định way that things on the website behave — as we said above sầu, it is sometimes referred lớn as normal flow, because without any other instruction, our boxes lay out as bloông chồng 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 blochồng. The first is a paragraph, which has a border added in CSS. The browser renders this as a bloông chồng box, so the paragraph begins on a new line, và expands to lớn the full width available to it.

The second is a menu, which is laid out using display: flex. This establishes flex layout for the items inside the container, however, the danh sách itself is a block box and — lượt thích the paragraph — expands khổng lồ the full container width and breaks onto a new line.

Below this, we have a block-level paragraph, inside which are two elements. These elements would normally be inline, however, one of the elements has a class of bloông chồng, and we have phối it to display: bloông chồng.

We can see how inline elements behave in this next example. The elements in the first paragraph are inline by mặc định & so do not force line breaks.

We also have sầu a element which is phối to lớn display: inline-flex, creating an inline box around some flex items.

Finally, we have two paragraphs both set to lớn display: inline. The inline flex container and paragraphs all run together on one line rather than breaking onlớn new lines as they would vì chưng if they were displaying as block-cấp độ elements.

In the example, you can change display: inline to lớn display: bloông chồng or display: inline-flex to display: flex to lớn toggle between these display modes.

You will encounter things like flex layout later in these lessons; the key thing to lớn rethành viên for now is that changing the value of the display property can change whether the outer display type of a box is bloông chồng 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 Mã Sản Phẩm applies to lớn bloông xã boxes, inline boxes only use some of the behavior defined in the box Mã Sản Phẩm. The mã sản phẩm defines how the different parts of a box — margin, border, padding, and content — work together lớn 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 sầu the:

The below diagram shows these layers:

*


The standard CSS box model


In the standard box Mã Sản Phẩm, if you give sầu a box a width and a height attribute, this defines the width và height of the content box. Any padding & border is then added to that width & height lớn 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, và 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), và the height 210px (150 + 25 + 25 + 5 + 5), as the padding và border are added khổng lồ the width used for the nội dung box.

*


Note: The margin is not counted towards the actual kích cỡ 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 lớn the margin.


The alternative CSS box model


You might think it is rather inconvenient to have to add up the border và padding lớn get the real kích thước of the box, và you would be right! For this reason, CSS had an alternative sầu box mã sản phẩm 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 sầu would give the below result (width = 350px, height = 150px).

*

By default, browsers use the standard box Mã Sản Phẩm. If you want to turn on the alternative model for an element you vị so by setting box-sizing: border-box on it. By doing this you are telling the browser to lớn take the border box as the area defined by any kích cỡ you set.

.box box-sizing: border-box; If you want all of your elements to use the alternative sầu box mã sản phẩm, và this is a comtháng choice aý muốn zerovn.nets, mix the box-sizing property on the element, then mix all other elements to inherit that value, as seen in the snippet below. If you want to lớn underst& 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 sầu box Model, with no mechanism available lớn switch.

Xem thêm: Cách Trở Thành Fan Cứng - Trên Facebook Nhanh Nhất


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 lớn use the alternative box Model.

Can you change the kích cỡ of the second box (by adding CSS khổng lồ the .alternate class) to lớn make it match the first box in width và height?


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


Use browser DevTools lớn view the box model


Your browser zerovn.net tools can make understanding the box Model far easier. If you inspect an element in Firefox"s DevTools, you can see the kích cỡ of the element plus its margin, padding, & border. Inspecting an element in this way is a great way to lớn find out if your box is really the kích thước you think it is!

*


Margins, padding, and borders


You"ve already seen the margin, padding, and border properties at work in the example above sầu. The properties used in that example are shorthands và allow us to lớn set all four sides of the box at once. These shorthands also have sầu 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 sầu or negative sầu values. Setting a negative margin on one side of your box can cause it to lớn overlap other things on the page. Whether you are using the standard or alternative box model, the margin is always added after the form 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 khổng lồ see how the box is pushed around due khổng lồ the margin creating or removing space (if it is a negative margin) between this element và the containing element.

Margin collapsing

A key thing khổng lồ understand about margins is the concept of margin collapsing. If you have sầu two elements whose margins touch, và both margins are positive, those margins will combine khổng lồ become one margin, which is the form size of the largest individual margin. If one or both margins are negative sầu, the amount of negative sầu 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 sầu collapsed together so the actual margin between the boxes is 50 pixels & not the total of the two margins.

You can thử nghiệm this by setting the margin-top of paragraph two to lớn 0. The visible margin between the two paragraphs will not change — it retains the 50 pixels mix in the bottom-margin of paragraph one. If you phối it lớn -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 vị và vì chưng not collapse. For further information see the detailed page on mastering margin collapsing. The main thing to rethành viên for now is that margin collapsing is a thing that happens. If you are creating space with margins & don"t get the space you expect, this is probably what is happening.


The border is drawn between the margin and the padding of a box. If you are using the standard box mã sản phẩm, the kích cỡ of the border is added to lớn the width & height of the box. If you are using the alternative sầu box model then the form size of the border makes the nội dung box smaller as it takes up some of that available width & 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 phối the width, style, or color of all four borders at once using the border property.

To mix the propertiesof each side individually, you can use:

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

To mix the width, style, or color of a single side, you can use one of the most granular longh& properties:

In the example below we have sầu used various shorthands và longhands to lớn create borders. Have sầu a play around with the different properties khổng lồ kiểm tra that you understand how they work. The MDoanh Nghiệp pages for the border properties give you information about the different styles of border you can choose from.


The padding sits between the border and the nội dung area. Unlượt thích margins you cannot have sầu negative sầu amounts of padding, so the value must be 0 or a positive value. Any background applied lớn your element will display behind the padding, & it is typically used to push the nội dung 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 khổng lồ 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 và whatever is inside the element.


All of the above sầu applies fully to lớn blochồng boxes. Some of the properties can apply to inline boxes too, such as those created by a element.

In the example below, we have a inside a paragraph & have applied a width, height, margin, border, and padding lớn it. You can see that the width & height are ignored. The vertical margin, padding, và border are respected but they do not change the relationship of other nội dung khổng lồ our inline box và so the padding & border overlaps other words in the paragraph.Horizontal padding, margins, & borders are respected& will cause other content to lớn move away from the box.


There is a special value of display, which provides a middle ground between inline & block. This is useful for situations where you vì chưng not want an sản phẩm to break onto lớn a new line, but vì want it lớn respect width & height & avoid the overlapping seen above.

An element with display: inline-blochồng does a submix of the bloông chồng things we already know about:

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

It does not, however, break onto lớn a new line, và will only become larger than its nội dung if you explicitly add width và height properties.

In this next example, we have added display: inline-bloông xã to our element. Try changing this lớn display: block or removing the line completely lớn see the difference in display models.

Where this can be useful is when you want to lớn give a links a larger hit area by adding padding. is an inline element like ; you can use display: inline-block to allow padding khổng lồ be set on it, making it easier for a user lớn cliông chồng the link.

You see this fairly frequently in navigation bars. The navigation below is displayed in a row using flexbox and we have sầu added padding khổng lồ the element as we want lớn be able khổng lồ change the background-color when the is hovered. The padding appears to lớn overlap the border on the element. This is because the is an inline element.

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


We have sầu covered a lot inthis article, but can you remember the most important information? You can find some further tests to lớn verify that you"ve retained this information before you move on — see Test your skills: The Box Model.


That"s most of what you need lớn understvà about the box mã sản phẩm. You may want to lớn return khổng lồ this lesson in the future if you ever find yourself confused about how big boxes are in your layout.

Xem thêm: Cách Khôi Phục Tin Nhắn Zalo Đã Xóa Trên Zalo, Facebook, Viber, Iphone

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.


Last modified: Feb 27, 2021, by MDN contributors

Change your languageSelect your preferred language English (US)EspañolFrançais日本語한국어Português (doBrasil)Русский中文 (简体) Change language
Getting started with the Web Introduction khổng lồ HTML Multitruyền thông media và embedding HTML tables CSS first steps CSS building blocks Styling text CSS layout JavaScript first steps JavaScript building blocks Introducing JavaScript objects Asynchronous JavaScript Client-side website APIs Vi xử lý Core forms learning pathway Advanced forms articles Accessibility guides Accessibility assessment Client-side website development tools Introduction to client-side frameworks React Ember Vue Svelte Angular Git & GitHub Cross browser testing First steps Django website framework (Python) Express Web Framework (node.js/JavaScript) Common questions