![](/img/trans.png)
[英]How to set flex items to equal width according to the item with the longest content?
[英]flex item width is always equal to intrinsic width of image content
目标
我的理解
问题
容器 div(child) 的宽度等于图像的固有宽度,而不是按比例缩小图像的新宽度,在容器 div(child) 的右侧留下额外的空间。
<html>
<head>
<style>
.parent {
display: flex;
width: 1000px;
height: 400px;
padding: 10px 0px;
background-color: red;
}
.child {
padding: 10px 0px;
background-color: blue;
}
.child > img {
height: 100%;
}
</style>
</head>
<body>
<div class="parent">
<div class="child">
<img src="https://cdn.pixabay.com/photo/2015/04/19/08/32/marguerite-729510_960_720.jpg" alt="some img">
</div>
</div>
</body>
</html>
.parent { display: flex; width: 1000px; height: 400px; padding: 10px 0px; background-color: red; }.child { padding: 10px 0px; background-color: blue; }.child > img { height: 100%; width: 100%; object-fit: cover; }
<html> <body> <div class="parent"> <div class="child"> <img src="https://cdn.pixabay.com/photo/2015/04/19/08/32/marguerite-729510_960_720.jpg" alt="some img"> </div> </div> </body> </html>
您可以将图像的宽度设置为 100%,这样它将占用整个 div。 为了使图像不丢失像素,您可以添加object-fit:cover;
这是工作示例https://codepen.io/maha986/pen/BaWqrGb
如果你想减小子 div 的大小,那么你可以将它的宽度设置为你想要的任何值
你可以让你的孩子和图像造型像这样
.child {
padding: 10px 0px;
width:500px;
background-color: blue;
}
.child > img {
height: 100%;
width:100%;
}
我不确定这是否是正确的方法,但我最终通过添加height: 100%;
解决了这个问题。 到.child
以及到.child > img
。 这是最终代码:
<html>
<head>
<style>
.parent {
display: flex;
width: 1000px;
height: 400px;
padding: 10px 0px;
background-color: red;
}
.child {
height: 100%;
background-color: blue;
}
.child > img {
height: 100%;
}
</style>
</head>
<body>
<div class="parent">
<div class="child">
<img src="https://cdn.pixabay.com/photo/2015/04/19/08/32/marguerite-729510_960_720.jpg" alt="some img">
</div>
</div>
</body>
</html>
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.