简体   繁体   中英

cannot eliminate space between 2 horizontal divs inside containing div

Should be easy, right? Just set the outer containing div's padding to zero, and set the two side-by-side divs inside the outer div to have margin:0 but that's having no effect on the space between the 2 horizontal divs. What I need is the red-outlined left div to touch the green-outlined right-side div.

Despite my effort using padding and margin, the space between the 2 divs will not go away.

I have looked at many answers on SO but so far no one's broken it down to this simple example -- my fiddle shows this issue, at

http://jsfiddle.net/Shomer/tLZrm/7/

And here is the very simple code:

<div style="border: 4px solid blue; white-space:nowrap; margin:0; padding:0; width:80%">

   <div style="display:inline-block; width:45%; overflow:hidden; margin:0; border: 1px solid red"> Flimmy-flammy
    </div>

    <div style="display:inline-block; width:50%; overflow:hidden; margin:0px; border: 1px solid green"> Hambone-Sammy
    </div>

</div>

The space rendered between your divs is the whitespace (represented as dots), collapsed, in:

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

Instead, try coding like this:

    </div><div>

and the gap will vanish.

Use the float property.

Example with div { float: left; } div { float: left; } : http://jsfiddle.net/tLZrm/10/ .

The whitespace in the source between inline blocks leads to a gap in the layout. By removing the space (whether it's a single space or some line breaks doesn't matter) the elements will touch as intended.

Formatting of the code can be retained at a slight cost, either by commenting out the whitespace or by making the whitespace occur within tags.

Using comments:

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

Placing linebreak inside tag:

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

Try this:

<div style="border: 4px solid blue; margin:0; padding:0; width:80%; height: 50px;">

   <div style="float:left; display:inline-block; width:45%; overflow:hidden; border: 1px solid red;"> Flimmy-flammy
    </div>

    <div style="float: left; display:inline-block; width:50%; overflow:hidden; border: 1px solid green;"> Hambone-Sammy
    </div>

</div>  

Like @Juan Lanus said in his answer, it is the whitespace causing your issue.

An additional solution is to set font-size: 0px on the containing div.

But you will need to then also set font-size: initial (or to a non-zero value) on the children div so you can still see your text.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM