Image size is different with the presence and absence of position:relative; at .container and position:absolute; at .container img(child).
The code below works fine ( the image did not mess up the equally sized grid ). However, when both positions are removed, the grid doesn't follow the coded size ( in this case its repeat(3,1fr) and repeat(4, 1fr) )
HTML:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
<link rel="stylesheet" href="issue.css">
</head>
<body>
<main>
<div class="container">
<img src="./assets/pic/pic.jpg" alt="">
</div>
</main>
</body>
</html>
CSS:
*,
html,
body {
width: 100%;
height: 100%;
box-sizing: border-box;
margin: 0;
padding: 0;
}
main {
width: 100%;
height: 100%;
display: grid;
grid-template-columns: repeat(3, 1fr);
grid-template-rows: repeat(4, 1fr);
}
.container {
grid-row: 2/3;
grid-column: 1/2;
width: 100%;
height: 100%;
position: relative;
}
.container img {
position: absolute;
height: 100%;
width: auto;
display: block;
}
Edit:
When I use object-fit:contain;, overflow:hidden; is a must in it.
My question is why is overflow:hidden; necessary to control the size of image? (HTML code is same as above, CSS code is below)
CSS:
*,
html,
body {
width: 100%;
height: 100%;
box-sizing: border-box;
margin: 0;
padding: 0;
}
main {
width: 100%;
height: 100%;
display: grid;
grid-template-columns: repeat(3, 1fr);
grid-template-rows: repeat(4, 1fr);
}
.container {
grid-row: 2/3;
grid-column: 1/2;
width: 100%;
height: 100%;
overflow: hidden;
}
.container img {
object-fit: contain;
height: 100%;
width: auto;
display: block;
}
Note: 1.This is most likely not a browser bug as Mozilla and Chrome produce the same result. 2.The image can be any aspect ratio as long as it is larger than the container (for my case i used 512px × 768px)