Why is table-layout: fixed affecting the width of the parent element?

后端 未结 3 1170
感情败类
感情败类 2020-12-31 07:45

Can someone explain why my div with table-layout:fixed is changing the width of its parent element (body in this case) to make it 100%

3条回答
  •  轻奢々
    轻奢々 (楼主)
    2020-12-31 08:16

    In your second example,

    body {
      border   : 2px solid red;
      height   : 100vh;
      margin   : 0;
      padding  : 0;
      position : absolute;
    
    }
    
    .c {
      display : table;
      width   : 80%;
      outline : 2px solid blue;
      /* table-layout : fixed; */
    }
    

    You have absolutely positioned the body, so it's taken out of normal flow and it doesn't influence the positioning or sizing of its .c child.

    So the width of .c isn't 80% of the body as you might initially expect.

    You can however use units like pixels or vw to set the width of .c and the result will be more intuitive, like this.

    .c {
      display : table;
      width   : 80vw; 
      outline : 2px solid blue;
      /* width : 80%;  */
      /* table-layout : fixed; */
    }
    

    Similarly, when you use table-layout:fixed; your browser uses an algorithm to calculate the width of the table which is similar to using units like pixels or vw to calculate the width for the table.

    To quote from the W3C spec

    17.5.2.1 Fixed table layout With this (fast) algorithm, the horizontal layout of the table does not depend on the contents of the cells ...

提交回复
热议问题