2017-03-01 54 views
0

我试图放置宽度各为50%的两个div,但某种程度上它不在同一行上显示,但如果我做了49%,它会堆叠在同一行中。任何人都可以告诉我我在做什么错了代码(更感兴趣知道原因比解决方案)。内联两个div并排 - CSS

CSS -

* { 
    padding: 0; 
    margin: 0; 
} 
.wrapper { 
    width: 100%; 
} 

.left-c { 
    width: 50%; 
    background: #3EF00C; 
    display: inline-block; 
} 

.right-c { 
    width: 50%; 
    background: #2E4E6E; 
    display: inline-block; 
} 

HTML -

<div class="wrapper"> 
    <div class="left-c"> 
     <p>LEFT ----- This is going to be some random text placed in a a left container inside the wrapper. I hope this text will suffice the requirement.</p> 
    </div> 
    <div class="right-c"> 
     <p>This is going to be some random text placed in a a right container inside the wrapper. I hope this text will suffice the requirement. ----- RIGHT</p> 
    </div> 
</div> 

JS小提琴 - https://jsfiddle.net/no0chhty/1/

+0

https://jsfiddle.net/no0chhty/4/ – mika

回答

4

这是一个经典的问题与inline-block类型的元素。不幸的是,他们考虑到文档空白,包括空白字符。对此有多种解决方案,但我倾向于使用的解决方案涉及将其父元素设置为font-size: 0,然后将内联块的字体大小重置为所需的值。

了解更多关于此这里:https://css-tricks.com/fighting-the-space-between-inline-block-elements/

+0

真棒,这个理论是真的有用+1 :) – Nesh

1

添加浮动:左;对类“左-C”

.left-c { 
      width: 50%; 
      background: #3EF00C; 
      display: inline-block; 
     float:left; 
     } 

请查看FIDDLE

0

替换这个CSS

* { 
    padding: 0; 
    margin: 0; 
} 
    .wrapper { 
    width: 100%; 
    display:flex 
    } 

    .left-c { 
    width: 50%; 
    background: #3EF00C; 
    } 

    .right-c { 
    width: 50%; 
    background: #2E4E6E; 
    } 
0
<div class="wrapper"> 
    <div class="left-c"><p></p></div><!----><div class="right-c"><p></p></div> 
</div> 

将left-c的结束标记与right-c的开始标记之间的注释解决问题。

Example

1

变化display: inline-blockdisplay: table-cell 像这样两部分:

.left-c { 
    width: 50%; 
    background: #3EF00C; 
    display: table-cell; 
} 

.right-c { 
    width: 50%; 
    /* 49% works well */ 
    background: #2E4E6E; 
    display: table-cell; 
} 

Here is the JSFiddle demo