码迷,mamicode.com
首页 > Web开发 > 详细

margin properties in CSS

时间:2015-05-28 10:48:34      阅读:127      评论:0      收藏:0      [点我收藏+]

标签:

In sometime, we want to center one div in our layout, but css doesn‘t provide one property for this.

we should use margin properties to implement.

First let we see the standard explanation about Margin in W3Schools.

Margin

The margin clears an area around an element (outside the border). The margin  does not have a background color, and is completely transparent.

The top, right, bottom, and left margin can be changed independently using separate properties. A shorthand margin property can also be used, to change all margins at once.

Possible Values

ValueDescription
auto The browser calculates a margin
length Specifies a margin in px, pt, cm, etc. Default value is 0px
% Specifies a margin in percent of the width of the containing element
inherit Specifies that the margin should be inherited from the parent element

Center one div will use margin auto property.

With W3school explanation, we still don‘t understand the exact mean of auto; let‘s have a look at below screenshot for explanation.

 

技术分享

we have two divs named as ‘content‘ and ‘centerContent‘.

for ‘content‘ div, it width is 500px;

for ‘centerContent‘ div, it width is 300px;

if we setup ‘centerContent‘ div margin property as

margin:0 auto;

it means

margin-top:0;

margin-right:auto;

margin-bottom:0;

margin-left:auto;

Css will calculation the margin-right and margin-left by this rule:

(‘content‘ div width - ‘centerContent‘ div width)/2 = (500-300)/2 = 100px; the real margin by calculation is:

margin-top:0;

margin-right:100px;

margin-bottom:0;

margin-left:100px;

in this way, it will center ‘centerContent‘ div as we expected.

if we also want to the text in this div also is also in center, we should add one additional property like this

text-align:center;

in one word, three properties should setup for this div:

width,margin and text-align.

 

margin properties in CSS

标签:

原文地址:http://www.cnblogs.com/pureni/p/4535226.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!