Billy Billy - 10 days ago 5
CSS Question

Removing 'white-space' of hidden images

I have a list of images that I would like to hide/show based on which

<li>
element is clicked. I have been able to do this successfully, however, there is still the white space below/above the image that is showing. Here is the code I am currently using:

HTML

<div class="img-container">
<img id="img1" src="img/image1.jpg" />
<img id="img2" src="img/image2.jpg" />
<img id="img3" src="img/image3.jpg" />
</div>


CSS

.img-container{
text-align: center;
visibility: hidden;
margin-top: 20px;
}


JS

var img1 = document.getElementById('img1');
var img2 = document.getElementById('img2');
var img3 = document.getElementById('img3');

("li:nth-child(2)").on('click', function() {
img1.style.visibility = 'visible';
img2.style.visibility = 'hidden';
img3.style.visibility = 'hidden';
});
("li:nth-child(3)").on('click', function(){
img2.style.visibility = 'visible';
img1.style.visibility = 'hidden';
img3.style.visibility = 'hidden';
});
("li:last-child").on('click', function() {
img3.style.visibility = 'visible';
img2.style.visibility = 'hidden';
img1.style.visibility = 'hidden';
});


I have tried playing around with the
display: hidden
css property paired with
.toggle()
but cannot seem to quite get it working correctly. I have tried searching for this but cannot find anything on removing the white space the hidden image is holding. Am relatively new to JS/jQuery. Thanks.

Answer

You could use the css property display and values none and block. The display property specifies if/how an element is displayed.

replace for visible img:

img1.style.visibility = 'visible';

for:

$("#img1").css("display", "block");

And replace for invisible img:

img1.style.visibility = 'hidden';

for:

$("#img1").css("display", "none");

Could use more useful inline-block instead block for lists.

Comments