【问题标题】:Img in flex container taking extra space?flex容器中的img占用额外空间?
【发布时间】:2021-09-10 10:02:43
【问题描述】:

HTML:(有 5 个这样的li's)

 <ul id='today-forecast'>
            <li class='today-item'>
                <div class='time'>Time</div>
                <img class='icon'></img>
                <div class='temp'>Temp</div>
            </li>
 </ul>

CSS:

#today-forecast {
  display: flex;
  list-style: none;
  align-items: center;
  justify-content: center;
}
#today-forecast .today-item {
  flex-grow: 1;
  display: flex;
  flex-direction: column;
  justify-content: flex-start;
  align-items: center;
  background-color: blue;
}

#today-forecast .today-item img{
  display: block; background-color: blue; }

JS

export function iconSetter(img, name) {
  //img <-img tag selected from document, name <- name of icon
  name = '01n' //from: https://openweathermap.org/weather- 
               //conditions
  img.src = `http://openweathermap.org/img/wn/${name}@2x.png`; 
}

使用 flexbox 网格线预览:

背景颜色表明问题可能不在于图像,而在于容器。 .today-item 的孩子没有 flex-grow: 1。我还尝试了 justify-content: flex-start,但它没有用。设置高度并不能解决这里的问题,但它可以解决我页面的另一部分。

【问题讨论】:

  • 添加代码sn-p。图片使用一些在线图片地址。
  • @SuryanshSingh 完成
  • 您问题中的代码没有重现问题。

标签: html css image flexbox


【解决方案1】:

你的&lt;img&gt;标签是不是错了。&lt;img&gt;标签是空元素,所以它不应该有结束标签。 要移除图标周围的多余空间,我们可以裁剪它。

#today-forecast {
  display: flex;
  list-style: none;
  align-items: center;
  justify-content: center;
}

#today-forecast .today-item {
  flex-grow: 1;
  display: flex;
  flex-direction: column;
  justify-content: flex-start;
  align-items: center;
  background-color: blue;
}

#today-forecast .today-item span {
  width: 50px;
  height: 50px;
  overflow: hidden;
}

#today-forecast .today-item img {
  width: 100px;
  height: 100px;
  margin: -25px 0 0 -25px;
}
 <ul id='today-forecast'>
   <li class='today-item'>
     <div class='time'>Time</div>
     <span><img class="icon" src="http://openweathermap.org/img/wn/01n@2x.png"></span>
     <div class='temp'>Temp</div>
   </li>
 </ul>

【讨论】:

  • 修复了,没有改变。
  • @GoldCredential 运行此代码 sn-p。你需要这样的东西吗。如果需要,更改图标大小。
  • 我想在我的问题中消除图片中图像周围不必要的空间。
  • @GoldCredential 现在试试运行代码sn-p,现在解决你的问题了吗?
  • 它不适合我的布局
猜你喜欢
  • 1970-01-01
  • 2020-06-12
  • 1970-01-01
  • 2018-06-11
  • 1970-01-01
  • 1970-01-01
  • 2012-01-03
  • 2020-11-01
  • 2012-02-18
相关资源
最近更新 更多