Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Strange padding between image and a span

Tags:

html

css

I have a strange padding between image and a span, I can not get rid of.

<div>
    <img src="http://placehold.it/100x100" />
    <span>hello</span>
</div>

img{
    padding:20px;
    background: red;
}

span{
    width: 300px;
    background-color: blue;
    display: inline-block;
    vertical-align: top;
    height: 100%;
}

As you see in this fiddle, I have some space between red and blue elements. And no matter what I do, I can not get rid of it. Also I would be grateful is someone can tell me why my height: 100%; does not work for the second element (it should be the same height as image).

like image 433
Salvador Dali Avatar asked Jul 04 '14 00:07

Salvador Dali


1 Answers

There is a strange padding because there is a space between the <img> and <span> in the html source.

<div>
    <img src="http://placehold.it/100x100" />
    <span>hello</span>
</div>

Removing the space would eliminate the padding.

<div>
    <img src="http://placehold.it/100x100" /><span>hello</span>
</div>

But that's probably not what you are after (read on). As per your second question, the reason 100% doesn't work is because the <div> isn't given a height and there is nothing to base the percentage height on. The <div> height here is the result of the height of its contents. It takes the height of the taller element so that it can accommodate both.

So what you are actually looking for is display: table. Placing the image and text side by side is very easily achieved with tables.

div {
    display: table;
}

img {
    display: table-cell;
    padding:20px;
    background: red;
}

span {
    display: table-cell;
    width: 300px;
    background-color: blue;
    vertical-align: top;
    height: 100%;
}

See demo here.

like image 120
Antony Avatar answered Nov 14 '22 22:11

Antony