1

I have and image element wrapped with a div:

 <div id="main_image_wrapper">
    <img id="main_image" src="image.jpg" />
 </div>

And, It is fine until there is no image to show. When the image.jpg does not exist, I still want to preserve the layout (I will use that later in javascript), So the code will be:

 <div id="main_image_wrapper">
    <img id="main_image"  />
 </div>

I expect this div element does not occupy (vertical) space, But unfortunately, it does. I tried to play with line-height:

  div#main_image_wrapper{line-height:1px;}

or

  div#main_image_wrapper{line-height:0;}

But the resultant div height will not be less than 6px.

When I use:

  img#main_image{display:block;}

this extra space will vanish. But I can not use block image in the page layout.

How can I remove this unwanted 6 px space when the img is empty?

Thank You Very Much.

jonrsharpe
  • 115,751
  • 26
  • 228
  • 437
Ormoz
  • 2,975
  • 10
  • 35
  • 50

4 Answers4

3

Maybe you can hide images without a src:

img:not([src]) {
   display: none;
}

Technically, an img without src attribute isn't valid though. There are ways around this, as is discussed in the question What's the valid way to include an image with no src?. But if you change that, you will also need to change the CSS, of course. :)

To solve this problem, use this valid html:

 <div id="main_image_wrapper">
    <img id="main_image" src="data:image/gif;base64,R0lGODlhAQABAAD/ACwAAAAAAQABAAACADs="  />
  </div>

and by the following css, prevent occupying space:

 img#main_image[src="data:image/gif;base64,R0lGODlhAQABAAD/ACwAAAAAAQABAAACADs="]
             {display:none;}
Community
  • 1
  • 1
GolezTrol
  • 114,394
  • 18
  • 182
  • 210
1

Why don't you use a different class, say noImg, for that case?

div.noImg {
  display: none;
}

Edit: I assume you are editing the div / img with Javascript, otherwise you wouldn't quite be able to edit the src attribute of the img element, right?

evilham
  • 346
  • 3
  • 12
0

Try this it will help you. Just use space after image tag like &nbsp; and then you can play with line height;

#main_image_wrapper{
    border:1px solid blue;
    lineheight:40px;
}


 
<div id="main_image_wrapper">
    <img id="main_image"  /> &nbsp;
 </div>
0

jsfiddle demo

css

#main_image_wrapper{
    border:1px solid blue;
    background:blue;
}
img{
    display: block;
}

html

 <div id="main_image_wrapper">
    <img id="main_image"  />
 </div>
kasper Taeymans
  • 6,950
  • 5
  • 32
  • 51