水平对齐方式

inline-block
text-align

原理:子元素设置成行内块状元素,父元素设置文本居中对齐也能使其生效

#parent{text-align: center;}
#child {display: inline-block;}
<!DOCTYPE html>
<html>

  <head>
    <meta charset="utf-8">
    <title></title>
    <style>
      #parentA,
      #parentB {
        width: 200px;
        height: 200px;
        text-align: center;
        background-color: red;
      }

      #childA {
        width: 100px;
        height: 100px;
      }

      #childA,
      #childB {
        display: inline-block;
        background-color: green;
      }
    </style>
  </head>

  <body>
    <p>子元素固定高宽A</p>
    <div id="parentA">
      <div id="childA">A</div>
    </div>
    <p>子元素不定高宽B</p>
    <div id="parentB">
      <div id="childB">B</div>
    </div>
  </body>

</html>

优点:

1) 不需要设置子元素具体宽度;
2) 兼容性好,甚至可以兼容ie6、ie7;

缺點:

1) 因为text-align是继承样式,会导致下级所有元素文字生效

评论

暂无评论