我有一个页面显示了一些电影封面,并且在大显示器上它们显示得很好,但是随着浏览器窗口的缩小,我希望图像在换行之前在宽度(和高度成比例)上调整自己的大小,直到达到一定的大小。
要确切了解我的意思,请查看:http://www.samuelgoldwynfilms.com/films 我想要相同的行为。
这是我创建的示例。
:root {
box-sizing: border-box;
}
*,
*::before,
*::after {
box-sizing: inherit;
}
body {
margin: 0;
padding: 0;
}
.flex-container {
display: flex;
flex-wrap: wrap;
}
img {
max-width: 100%;
height: 500px;
}
.box {
height: 500px;
}
.box {
margin-left: 1em;
}
.box-1 {
background-color: lightgray;
}
.box-2 {
background-color: lightsalmon;
}
.box-3 {
background-color: lightseagreen;
}
.box-4 {
background-color: lightblue;
}
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<link rel="stylesheet" href="learn-flex.css">
<title>Learn Flex</title>
</head>
<body>
<div class="flex-container">
<div class="box box-1">
<img src="https://images-na.ssl-images-amazon.com/images/I/81PWF-yAEyL._AC_SL1100_.jpg" alt="">
</div>
<div class="box box-2">
<img src="https://images-na.ssl-images-amazon.com/images/I/71VDlRubWtL._AC_SY741_.jpg" alt="">
</div>
<div class="box box-3">
<img src="https://fanart.tv/fanart/movies/12230/movieposter/101-dalmatians-5a529ef29b36c.jpg" alt="">
</div>
<div class="box box-4">
<img src="https://i.pinimg.com/originals/b5/46/7f/b5467f2221d78d204b5a44c8d57d516f.jpg" alt="">
</div>
</div>
</body>
</html>
在这个阶段,flexbox 只对 item 进行包装,而不会在包装前尝试将它们缩小到一定的大小。
如果有任何建议,我将不胜感激。
答案 0 :(得分:1)
我认为问题是当你给 .box {height: 500px;} 而不是宽度时,它变得无法控制。对于响应式图片,我建议您使用带有 max-width:100% 和 height: auto 的 img。当您执行此图像时,会根据其父 div 调整自身大小,如果您为父 div 提供所需的任何大小,则可以更轻松地对其进行操作。 所以这里的代码;
:root {
box-sizing: border-box;
}
*,
*::before,
*::after {
box-sizing: inherit;
}
body {
margin: 0;
padding: 0;
}
.flex-container {
display: flex;
flex:0 0 100%;
width: 100%;
flex-wrap: nowrap;
}
img {
max-width: 100%;
height: auto;
object-fit:cover;
}
.box {
width: 300px;
max-height: 500px;
}
.box {
margin-left: 1em;
}
.box-1 {
background-color: lightgray;
}
.box-2 {
background-color: lightsalmon;
}
.box-3 {
background-color: lightseagreen;
}
.box-4 {
background-color: lightblue;
}
@media screen and (max-width:991px) {
.flex-container {
flex-wrap: wrap;
}
.box {
margin: 10px;
}
}
@media screen and (max-width:520px) {
.box {
margin: auto;
}
}
我还添加了 codepen 代码:https://codepen.io/ates_irem/pen/zYobMQr?editors=1100