【问题标题】:Trying to fit image inside a flex box in CSS试图将图像放入 CSS 中的弹性框内
【发布时间】:2022-02-08 19:36:56
【问题描述】:

这就是我希望页面拆分的方式,以便我可以拥有流畅的布局。

<div class="container">
  <div class="top">Top</div>
  <div class="image">image</div>
  <div class="footer">footer</div>
</div>

.container{
  height: 100vh;
  width: 100vw;
  display: flex;
  flex-direction: column;
}

.top {
  flex: 25%;
  width: 100%;
  background-color: red;
}

.image {
  flex: 50%;
  width: 100%;
  background-color: green;
}

.footer{
  flex: 25%;
  width: 100%;
  background-color:blue;
}

https://jsfiddle.net/9n7zmr60/

在图片部分,我想插入一张图片,我希望它与上面的比例相同(25% 50% 25%)。但是,当我尝试时,它会像下面这样被拉伸:

.container{
  height: 100vh;
  width: 100vw;
  display: flex;
  flex-direction: column;
}

.top {
  flex: 25%;
  width: 100%;
  background-color: red;
}

.image {
  flex: 50%;
  width: 100%;
  background-color: green;
  max-width: 100%;
  object-fit: contain;
  
}

.footer{
  flex: 25%;
  width: 100%;
  background-color:blue;
}

https://jsfiddle.net/qcnwu7fe/

请帮忙

【问题讨论】:

  • 您不应该在image 类上设置属性,而应在img 本身上设置属性。

标签: html css flexbox


【解决方案1】:

做这些改变:

.image {
  flex: 50%; /*delete this*/
  height: 50%;
  width: 100%;
  background-color: green;
}
img{
  height: 100%;
  width: 100%;
}

.container {
  height: 100vh;
  width: 100vw;
  display: flex;
  flex-direction: column;
}

.top {
  flex: 25%;
  width: 100%;
  background-color: red;
}

img {
  height: 100%;
  width: 100%;
}

.image {
  width: 100%;
  background-color: green;
  height: 50%;
}

.footer {
  flex: 25%;
  width: 100%;
  background-color: blue;
}
<div class="container">
  <div class="top">Top</div>
  <div class="image"><img src="https://static1.momsimage.com/wordpress/wp-content/uploads/2019/08/Kids-cartoons.jpg" alt=""></div>
  <div class="footer">footer</div>
</div>

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-10-27
    • 2014-12-29
    • 1970-01-01
    • 2018-09-07
    • 1970-01-01
    相关资源
    最近更新 更多