深入理解 margin

1. margin可以改变容器尺寸。

2. margin与百分比单位。(普通元素的百分比margin都是相对于父级的宽度计算的,

      绝对定位元素的百分比margin是相对于第一个定位祖先元素(relative/absolute/fixed)的宽度计算的。)

 例子: 宽高2:1自适应矩形

.box { background-color: olive;  overflow: hidden; }

.box > div { margin: 50%; }

3. 正确看待css的margin重叠。

   margin的计算法则: 1.正正取大值。 2. 正负值相加。3.负负最负值。

 例子: .list { margin-top : 15px; margin-bottom: 15px; },利用margin的上下间距重叠属性。

4.理解css中的margin auto。

img { display: block; width: 200px; margin : 0 auto;} /*图片水平居中.*/

设置div元素垂直居中。 (改变流的方向 writing-mode. 如下:)

<div class="father">

         <div class="son"></div>

</div>

.father { height: 200px; width: 100%; writing-mode: vertical-lr; }

.son { height: 100px; width: 500px; margin: auto; }

/*************************/

绝对定位的垂直居中.

.father { height: 200px; position: relative; }

.son { position: absolute; top: 0; right: 0; bottom: 0; left:0; width: 500px;height:100px; margin: auto; }

/*********************************************************************/

  margin负值定位。(margin负值可以改变(增加)空间尺寸。)

1.margin负值下的两端对齐。

<div class="box">

     <div class="ul">

         <div class="li">列表一</div>

         <div class="li">列表二</div>

          <div class="li">列表三</div>

     </div>

</div>

.box{ width: 1200px; margin: auto; background: orange;}

.ul { overflow: hidden; margin-right: -20px;}

.li { width: 386.66px; height: 300px; margin-right: 20px; background: green; float: left;}

/****************************************************************************************************/

2. margin负值下的等高布局。

例一: <div style="height: 200px;">

                    <img  height="300"  style="margin: 50px 0;">

             </div>

例二: . box { overflow: hidden; resize: vertical; }

             .child-orange, .child-green { margin-bottom: -600px; padding-bottom: 600px;}

              .child-orange { float:left; background: orange; }

              .child-green { float:left; background: green; }

/*****************************************************************************************/

3. margin负值下的两栏自适应布局.

<div  style="float:left; width: 100%;">

          <p style="margin-right: 170px;">左边文字,右边图片......</p>

</div>

<img width="150"  style="float: left; margin-left: -150px;">

// margin负值增加空间尺寸,margin正值减小空间尺寸。

/***********************************************************************/

margin无效的情况。

1. 内联元素的垂直margin是无效的。

2. margin重叠。

3. display: table-cell;   margin是无效的。

/**************************************************************************/

猜你喜欢

转载自blog.csdn.net/yijiupingfan0914/article/details/93625854