CSS two div width 50% in one line with line break in file

后端 未结 9 1249
囚心锁ツ
囚心锁ツ 2020-12-04 15:18

I try to build fluid layout using percentages as widths. Do do so i tried this:

A
相关标签:
9条回答
  • 2020-12-04 16:09

    Give this parent DIV font-size:0. Write like this:

    <div style="font-size:0">
      <div style="width:50%; display:inline-table;font-size:15px">A</div>
      <div style="width:50%; display:inline-table;font-size:15px">B</div>
    </div>
    
    0 讨论(0)
  • 2020-12-04 16:10

    The problem you run into when setting width to 50% is the rounding of subpixels. If the width of your container is i.e. 99 pixels, a width of 50% can result in 2 containers of 50 pixels each.

    Using float is probably easiest, and not such a bad idea. See this question for more details on how to fix the problem then.

    If you don't want to use float, try using a width of 49%. This will work cross-browser as far as I know, but is not pixel-perfect..

    html:

    <div id="a">A</div>
    <div id="b">B</div>
    

    css:

    #a, #b {
        width: 49%;
        display: inline-block; 
    }
    #a {background-color: red;}
    #b {background-color: blue;}
    
    0 讨论(0)
  • 2020-12-04 16:12

    The problem is that if you have a new line between them in the HTML, then you get a space between them when you use inline-table or inline-block

    50% + 50% + that space > 100% and that's why the second one ends up below the first one

    Solutions:

    <div></div><div></div>
    

    or

    <div>
    </div><div>
    </div>
    

    or

    <div></div><!--
    --><div></div>
    

    The idea is not to have any kind of space between the first closing div tag and the second opening div tag in your HTML.

    PS - I would also use inline-block instead of inline-table for this

    0 讨论(0)
提交回复
热议问题