When I click on an item in my grid, the content of that item is moved to a modal. The modal functions properly, but I noticed that when the content is removed from the item, a space appears above it.
I have found that using flexbox could solve this issue, but I am curious about understanding the underlying cause.
One key detail is that each item has three children - two with position: absolute
and one without a specific position.
It seems that setting all children to position: absolute
resolves the problem, but I want to know why there is a difference in outcome based on the content being present or not.
You can see the problem in action in this JSFiddle.
HTML Structure:
<div class="context">
<div class="grid">
<div class="item">
<div class="cover"> // has position: absolute
<h1>Title</h1>
</div>
<div class="img-wrapper"> // has position: absolute
<img/>
</div>
<div class="description"> // doesn't have a position defined
<p>Description...</p>
</div>
<div class="item">
// item content
</div>
</div>
</div>
The grid contains 8 items divided into two rows of 4 items each.
CSS Styling:
To achieve this layout, the following CSS rules are applied:
.grid {
margin-top: 100px;
font-size: 0; // to get all the items together
border: 1px solid red;
}
.item {
width: calc(100% / 4);
height: 100px;
position: relative;
display: inline-flex;
}
.description {
display: flex;
flex-direction: column;
justify-content: space-around;
top: 0;
bottom: 0;
}
.img-wrapper {
position: absolute;
top: 0;
bottom: 0;
left: 0;
right: 0;
}
img {
height: 100%;
width: auto;
display: block;
margin: auto;
}
.cover {
position: absolute;
top: 0;
bottom: 0;
width: 100%;
display: flex;
justify-content: center;
align-items: center;
}
Note: Additional CSS styling in the JSFiddle example does not affect the core structure causing the issue.
JavaScript Functionality:
The JavaScript code responsible for moving content to the modal is as follows:
let $itemNode;
let $itemContent;
$().ready(args => {
let $modal = $('#modal');
$('.item').click(function() {
$itemNode = $(this);
$itemContent = $(this).children();
$itemNode.css({visibility: 'hidden'});
$itemContent.appendTo($modal);
});
});