控制一个CSS网格内的图像的大小
我有一个css网格,有一堆区域和一个照片容器。控制一个CSS网格内的图像的大小
我不知道如何:
1)控制照片的大小,因此它被包含在网格区域内,并
2)保持照片的宽度在100%(因此等于它的容器)并且缩放容器的高度以适合照片。基本上,则窗口变得更小,照片的宽度变小,所以确实高度 - 拉标签,专辑和旋转元素,直到....
.container {
display: grid;
grid-template-columns: repeat(5, 1fr);
grid-template-rows: 40vh 30vh 30vh;
grid-gap: 10px;
grid-template-areas:
"info photo photo photo photo"
"comment photo photo photo photo"
"comment tag tag album rotate"
}
.photo {
grid-area: photo;
background: yellow;
}
.photo>img {
object-fit: cover;
width: 100%
}
.info {
grid-area: info;
background: pink;
}
.tag {
grid-area: tag;
background: teal;
}
.comment {
grid-area: comment;
background: green;
}
.album {
grid-area: album;
background: red;
}
.rotate {
grid-area: rotate;
background: blue;
}
<div class="container">
<div class="photo">
<img src="http://wallpaper-gallery.net/images/image/image-13.jpg" />
</div>
<div class="info">info</div>
<div class="tag">tag</div>
<div class="comment">comment</div>
<div class="album">album</div>
<div class="rotate">rotate</div>
</div>
这里有两个不同的问题。
我将解决第一个问题,它将图像包含在其容器中。你几乎拥有它。
您的代码:
.photo > img {
object-fit: cover;
width: 100%
}
你只需要在图像上指定的最大高度,它可能不会溢出容器:
.photo > img {
object-fit: cover;
width: 100%
max-height: 100%;
}
第二个问题,这是规模图像容器的大小,以及在图像变小时将下面的网格物体拖动起来,显得更加复杂。
这不是与图像有关的问题。事实上,您可以在尝试解决此问题时完全删除图像。
这是动态调整网格项目(图像容器)大小的问题。为什么当这个网格项目的尺寸受到grid-template-columns
和grid-template-rows
的控制时,会相对于图片尺寸改变尺寸?
另外,为什么底部的一行栅格项(tag
,album
,rotate
)会跟随图像容器向上或向下?他们将不得不退出他们的行。
缩放整个网格容器不会是一个问题。但它似乎只是想缩放一个网格项目(图像容器)。这很棘手。您可能正在查看其他容器,长度值为auto
,可能还有脚本。
这里的,如果你给图像行的auto
值会发生什么:jsFiddle demo
感谢您的指导。第一个问题/解决方案解决了我的头痛问题!你对第二部分是对的。我将解决它正在调整我正在使用的3种媒体布局(移动,平板电脑,笔记本电脑)的不同布局。我完全明白你的观点:-) – martin
如果你使用背景图像内的网格单元,而不是IMG标签的一个(没用过显示:网格还没有B/C它是如此新 - 酷!)
然后使用背景大小和背景位置,您可以在该单元格内正确调整大小。
.container {
display: grid;
grid-template-columns: repeat(5, 1fr);
grid-template-rows: 40vh 30vh 30vh;
grid-gap: 10px;
grid-template-areas: "info photo photo photo photo" "comment photo photo photo photo" "comment tag tag album rotate"
}
.photo {
grid-area: photo;
background: yellow;
height: 100%;
background-size: cover; /* <-- background size */
background-position: center; /* <-- background position */
}
.info {
grid-area: info;
background: pink;
}
.tag {
grid-area: tag;
background: teal;
}
.comment {
grid-area: comment;
background: green;
}
.album {
grid-area: album;
background: red;
}
.rotate {
grid-area: rotate;
background: blue;
}
<div class="container">
<div class="photo" style="background-image: url('https://thumbs.web.sapo.io/?epic=YmIzAEUIMb3pue+Zz8qV8QS/WuKmq0vrL/lWiluSn7SstKeeh7/UTTBAuDlhHFD6YC9+vaCHBQuNOXeVaHkjzTSE8tF3hMBev6512ha92Yc4kRw=&W=1200&H=627&crop=center&delay_optim=1')">
</div>
<div class="info">info</div>
<div class="tag">tag</div>
<div class="comment">comment</div>
<div class="album">album</div>
<div class="rotate">rotate</div>
</div>
我不认为你要完成可以用网格做什么。 – BrandonW