2017-03-01 50 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