Blogger Information
Blog 8
fans 0
comment 0
visits 4839
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
box-sizing属性和常用的元素居中方式
择善而从
Original
606 people have browsed it

box-sizing属性和常用的元素居中方式

box-sizing属性

box-sizing 属性定义了如何计算一个元素的总宽度和总高度,它有如下两个值:

  1. content-box 是默认值。如果设置一个元素的宽为100px,那么这个元素的内容区会有100px宽,并且任何边框和内边距的宽度都会被增加到最后绘制出来的元素宽度中。这意味着当调整一个元素的宽度和高度时需要时刻注意到这个元素的边框和内边距,布局时尤其烦人。
  2. border-box 设置的边框和内边距的值是包含在元素尺寸内。也就是说,如果将一个元素的width设为100px,那么这100px会包含它的border和padding,内容区的实际宽度是width减去(border + padding)的值。大多数情况下布局更方便,一般我们会使用这个值。
  1. div {
  2. width: 160px;
  3. height: 80px;
  4. padding: 20px;
  5. border: 8px solid yellow;
  6. background: green;
  7. }
  8. div {
  9. box-sizing: content-box;
  10. /* 元素宽度: 160px + (2 * 20px) + (2 * 8px) = 216px
  11. 元素高度: 80px + (2 * 20px) + (2 * 8px) = 136px
  12. */
  13. }

而使用box-sizing: border-box; 则不需要计算,实际尺寸直接与元素定义的相同。

  1. div {
  2. box-sizing: border-box;
  3. /* 元素宽度: 160px
  4. 元素高度: 80px
  5. */
  6. }

常用的元素居中方式

  • 行内元素

    1. 水平居中,使用text-align:center;
    2. 垂直居中,使用line-height:100px;
      设置子元素行高与父元素高度相同,行内元素即可垂直居中
  1. div {
  2. text-align: center;
  3. line-height: 100px;
  4. }
  • 块元素

    1. 水平居中,使用margin: auto;
    2. 垂直居中,使用padding:50px;上下挤压
  1. .box>div{
  2. margin: auto; /*水平居中 */
  3. }
  4. .box {
  5. padding: 50px; /*垂直居中 */
  6. }
Correcting teacher:天蓬老师天蓬老师

Correction status:qualified

Teacher's comments:太简洁了
Statement of this Website
The copyright of this blog article belongs to the blogger. Please specify the address when reprinting! If there is any infringement or violation of the law, please contact admin@php.cn Report processing!
All comments Speak rationally on civilized internet, please comply with News Comment Service Agreement
0 comments
Author's latest blog post
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!