Back

Explore Courses Blog Tutorials Interview Questions
0 votes
2 views
in Web Technology by (20.3k points)

Given this HTML and CSS:

span {

    display:inline-block;

    width:100px;

    background-color:palevioletred;

}

<p>

    <span> Foo </span>

    <span> Bar </span>

</p>

 Run code snippetExpand snippet

As a result, there will be a 4-pixel wide space between the SPAN elements.

Demo: http://jsfiddle.net/dGHFV/

I understand why this happens, and I also know that I could get rid of that space by removing the white-space between the SPAN elements in the HTML source code, like so:

<p>

    <span> Foo </span><span> Bar </span>

</p>

However, I was hoping for a CSS solution that doesn't require the HTML source code to be tampered with.

I know how to solve this with JavaScript - by removing the text nodes from the container element (the paragraph), like so:

// jQuery

$('p').contents().filter(function() { return this.nodeType === 3; }).remove();

Demo: http://jsfiddle.net/dGHFV/1/

But can this issue be solved with CSS alone?

1 Answer

0 votes
by (40.7k points)

You can solve the above problem with CSS alone, but there are no completely robust CSS fixes.

However, while this is a reasonable solution if you specifically need a CSS only fix, it's not what I recommend if you're free to change your HTML (as most of us are).

Use the code given below: 

<p>

    <span>Foo</span><span>Bar</span>

</p>

Try removing the whitespace in the HTML between the inline-block elements. This is easy and simple.

In HTML you can remove the whitespace this way:

<ul>

    <li>Item 1</li>

    <li>Item 2</li>

    <li>Item 3</li>

</ul>

You can do like this:

<ul>

    <li>Item 1</li><li>Item 2</li><li>Item 3</li>

</ul>

http://jsfiddle.net/thirtydot/dGHFV/1362/

Otherwise, try this:

<ul>

    <li>Item 1</li

    ><li>Item 2</li

    ><li>Item 3</li>

</ul>

  • Or else use the comments:

<ul>

    <li>Item 1</li><!--

    --><li>Item 2</li><!--

    --><li>Item 3</li>

</ul>

  • But, if you are using PHP or similar then do this:

<ul>

    <li>Item 1</li><?

    ?><li>Item 2</li><?

    ?><li>Item 3</li>

</ul>

  • Or, you can skip certain closing tags entirely this way:

<ul>

    <li>Item 1

    <li>Item 2

    <li>Item 3

</ul>

Another way is, you can now use flexbox to achieve many of the layouts that you may previously have used inline-block for:

 https://css-tricks.com/snippets/css/a-guide-to-flexbox/

Browse Categories

...