CSS Padding

# Margins

When two margins are touching each other vertically, they are collapsed. When two margins touch horizontally, they do not collapse.

Example of adjacent vertical margins:

Consider the following styles and markup:

div> some content div> div> some more content div> 

They will be 10px apart since vertical margins collapse over one and other. (The spacing will not be the sum of two margins.)

Example of adjacent horizontal margins:

Consider the following styles and markup:

span>somespan>span>contentspan> 

They will be 20px apart since horizontal margins don’t collapse over one and other. (The spacing will be the sum of two margins.)

Overlapping with different sizes

.top  margin: 10px; > .bottom  margin: 15px; > 
div class="top"> some content div> div class="bottom"> some more content div> 

These elements will be spaced 15px apart vertically. The margins overlap as much as they can, but the larger margin will determine the spacing between the elements.

Overlapping margin gotcha

.outer-top  margin: 10px; > .inner-top  margin: 15px; > .outer-bottom  margin: 20px; > .inner-bottom  margin: 25px; > 
div class="outer-top"> div class="inner-top"> some content div> div> div class="outer-bottom"> div class="inner-bottom"> some more content div> div> 

What will be the spacing between the two texts? (hover to see answer)

The spacing will be 25px. Since all four margins are touching each other, they will collapse, thus using the largest margin of the four.

Now, what about if we add some borders to the markup above.

div  border: 1px solid red; > 

What will be the spacing between the two texts? (hover to see answer)

The spacing will be 59px! Now only the margins of .outer-top and .outer-bottom touch each other, and are the only collapsed margins. The remaining margins are separated by the borders. So we have 1px + 10px + 1px + 15px + 20px + 1px + 25px + 1px. (The 1px’s are the borders. )

Collapsing Margins Between Parent and Child Elements:

h1>Titleh1> div> p>Paragraphp> div> 
h1  margin: 0; background: #cff; > div  margin: 50px 0 0 0; background: #cfc; > p  margin: 25px 0 0 0; background: #cf9; > 

In the example above, only the largest margin applies. You may have expected that the paragraph would be located 60px from the h1 (since the div element has a margin-top of 40px and the p has a 20px margin-top). This does not happen because the margins collapse together to form one margin.

# Apply Margin on a Given Side

# Direction-Specific Properties

CSS allows you to specify a given side to apply margin to. The four properties provided for this purpose are:

The following code would apply a margin of 30 pixels to the left side of the selected div. View Result

#myDiv  margin-left: 30px; height: 40px; width: 40px; background-color: red; > 
Parameter Details
margin-left The direction in which the margin should be applied.
30px The width of the margin.

# Specifying Direction Using Shorthand Property

The standard margin property can be expanded to specify differing widths to each side of the selected elements. The syntax for doing this is as follows:

The following example applies a zero-width margin to the top of the div, a 10px margin to the right side, a 50px margin to the left side, and a 100px margin to the left side. View Result

#myDiv  margin: 0 10px 50px 100px; height: 40px; width: 40px; background-color: red; > 

# Margin property simplification

p  margin: 1px; /* 1px margin in all directions */ /*equals to:*/ margin: 1px 1px; /*equals to:*/ margin: 1px 1px 1px; /*equals to:*/ margin: 1px 1px 1px 1px; > 
p  margin: 10px 15px; /* 10px margin-top & bottom And 15px margin-right & left*/ /*equals to:*/ margin: 10px 15px 10px 15px; /*equals to:*/ margin: 10px 15px 10px; /* margin left will be calculated from the margin right value (=15px) */ > 

# Horizontally center elements on a page using margin

As long as the element is a block, and it has an explicitly set width value, margins can be used to center block elements on a page horizontally.

We add a width value that is lower than the width of the window and the auto property of margin then distributes the remaining space to the left and the right:

#myDiv  width: 80%; margin: 0 auto; > 

In the example above we use the shorthand margin declaration to first set 0 to the top and bottom margin values (although this could be any value) and then we use auto to let the browser allocate the space automatically to the left and right margin values.

In the example above, the #myDiv element is set to 80% width which leaves use 20% leftover. The browser distributes this value to the remaining sides so:

# Negative margins

Margin is one of a few CSS properties that can be set to negative values. This property can be used to overlap elements without absolute positioning.

div display: inline; > #over margin-left: -20px; > 
Base div
"over">Overlapping div

# Example 1:

It is obvious to assume that the percentage value of margin to margin-left and margin-right would be relative to its parent element.

.parent  width: 500px; height: 300px; > .child  width: 100px; height: 100px; margin-left: 10%; /* (parentWidth * 10/100) => 50px */ > 

But that is not the case, when comes to margin-top and margin-bottom . Both these properties, in percentages, aren’t relative to the height of the parent container but to the width of the parent container.

.parent  width: 500px; height: 300px; > .child  width: 100px; height: 100px; margin-left: 10%; /* (parentWidth * 10/100) => 50px */ margin-top: 20%; /* (parentWidth * 20/100) => 100px */ > 

# Syntax

  • margin: ;
  • margin: , , ;
  • margin: , ;
  • margin: , , , ;
  • margin-top: ;
  • margin-right: ;
  • margin-bottom: ;
  • margin-left: ;

# Parameters

Parameter Details
0 set margin to none
auto used for centering, by evenly setting values on each side
units (e.g. px) see parameter section in Units

# Remarks

More on «Collapsing Margins»: here

Источник

Руководство CSS Margins

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

1- CSS Margin

CSS Margin используется для создания пространства вокруг элемента, вне границ элемента.

 /* Syntax: */ margin: top right bottom left; /* Example: */ margin: 5px 20px 30px 40px; 

Вместо того, чтобы предоставить 4 значения для CSS margin вы можете использовать 4 свойства (property) CSS margin-top, margin-right, margin-bottom, margin-left.

 margin-top: 5px; margin-right: 20px; margin-bottom: 30px; margin-right: 40px; 
 /* Apply to all four sides */ margin: 1em; margin: -3px; /* vertical | horizontal */ margin: 5px 10px; /* top | horizontal | bottom */ margin: 10px 20px 30px; 
auto Браузер автоматически расчитает margin для элемента.
% Определяет значение по % для margin, данное значение является % по отношению к ширине ближайшего предка элемента уровня блока (Block-level Element) содержащего текущий элемент. Смотрите так же объяснения в конце данной статьи.
px, cm, em. Определить точное значение по единице px, cm, em. Например 10px, 2cm, 3em.
inherit Значение у margin будет унаследовано от родительского элемента.

2- CSS Margin %

CSS margin принимает значение процента ( % ). Данное значение является процентом по отношению к ширине Containing Block. При этом, Containing Block является ближайшим элементом предком уровня блока ( block-level element) содержащим текущий элемент.

        

CSS Margin Percentage

I am a div (Block-Level Element)
I am a span (Inline Element)
width:100px; margin:10%;

3- CSS margin auto

CSS margin принимает значение auto. Это хорошее решение когда вы хотите выровнять элементы по центру по горизонтали.

      .center-div 

CSS Margin auto

margin-right: auto;

4- Margin for Inline Element

Примечание: CSS margin по вертикали (margin-top & margin-bottom) не влияет на строчный элемент (Inline Element). Например, по умолчанию является строчным элементом, margin по вертикали не влияет на него.

      div < background-color: yellow; >span 

CSS Margin for Inline Element

I am a div
I am a span. margin-top: 100px; margin-bottom: 100px; margin-left: 20px; margin-right: 20px;
I am a div

Если вы хотите чтобы margin по вертикали влиял на строчный элемент (Inline element) вам нужно превратить его в блочный элемент (Block-Level Element) или строчно-блочный элемент (Inline-block Element).

5- CSS margin collapsing

Нижнее и верхнее поля 2-х соседних блочных элементов (Block-level element) иногда объединяются друг с другом, образуя 1 единственное поле с наибольшим размером среди 2-х вышеуказанных полей. Данное действие называется схлапыванием полей (margin collapsing). Примечание: Схлапывание полей (margin collapsing) не происходит с элементами имеющими или .

      div < border:1px solid green; >button   

CSS Margin Collapsing

height:50px; margin-bottom:50px;

Если 2 блочных элемента (block-level element) являются смежными, они вызывают схлапывание полей (Смотрите пример выше). Но если 2-ой элемент устанавливает CSS , то не произойдет схлапывание.

      div < border:1px solid green; >p 

CSS Margin Collapsing

Margin Collapsing does not work with

height:50px; margin-bottom:50px;

Если родительский элемент не имеет border, padding, и первый дочерний элемент является блочным элементом (Block-level element) не имеющим , то схлапывание полей (margin collapsing) произойдет с margin-top дочернего элемента и другого элемента за пределами родительского.

      div < background: lavender; >p 

CSS Margin Collapsing (Parent and First Child)

This is a div

Child Paragraph 1 - margin-top: 30px;

Child Paragraph 2 - margin-top: 30px;

This parent element contains two paragraphs!

Если родительский элемент не имеет border, padding, и последний дочерний элемент являетсяя блочным элементом (Block-level element) без , то схлапывание полей (margin collapsing) произойдет с margin-bottom данного дочернего элемент и другого элемента за пределами родительского.

      div < background: lavender; >p 

CSS Margin Collapsing (Parent and last Child)

This parent element contains two paragraphs!

Child Paragraph 1 - margin-bottom: 30px;

Child Paragraph 2 - margin-bottom: 30px;

This is a div

Если элемент является пустым блоком, не имеющим border, padding, height, min-height, то его margin-top и margin-bottom схлопнутся (collapse) в значение.

      

CSS Margin Collapsing (Empty block)

height:40px;
height:50px;

Если учатствует отрицательный margin в схлапывании, то значение у использованного margin будет суммой наибольшей положительной margin и самой отрицательной margin.

View more Tutorials:

Это онлайн курс вне вебсайта o7planning, который мы представляем, он включает бесплатные курсы или курсы со скидкой.

  • * * Write quicker HTML5 and CSS 3; productivity hacks with emmet
  • Learning CSS
  • HTML5, CSS3 & JavaScript Workshop: Build 7 Creative Projects
  • HTML 5 and CSS 3 — tricks and workarounds
  • Ultimate HTML and CSS course for Absolute Beginners 2015
  • HTML CSS JavaScript: Most popular ways to code HTML CSS JS
  • CSS3 Master Series: CSS Animations, Transforms & Transitions
  • CSS Development (with CSS3!)
  • Web Design for Beginners: Real World Coding in HTML & CSS
  • * * Master the Basics of HTML5 & CSS3: Beginner Web Development
  • Create Beautiful Websites with CSS3
  • A Web Development Crash Course in HTML5 and CSS3
  • Mastering CSS3 Colors
  • CSS3 MasterClass — Transformations And Animations
  • * * Beginner Photoshop to HTML5 and CSS3
  • CSS and CSS3 Advanced
  • CSS3: Video QuickStart Guide
  • * * Mastering CSS 3.0 Selectors
  • Изучите HTML и CSS за несколько часов
  • Learn Html5 & CSS3 from scratch
  • Step-by-step HTML and CSS for Absolute Beginners
  • HTML5 and CSS for Beginner To Expert
  • Create Android and iOS App using HTML, CSS and JS
  • Build Real World Websites from Scratch using HTML5 and CSS3
  • HTML5 & CSS3 Site Design

Источник

Читайте также:  Сортировка прямым включением python
Оцените статью