html - 为什么以百分比表示的宽度与以像素表示的宽度产生不同的结果?

标签 html css flexbox horizontal-scrolling

我在布局的第二列中有一个水平滚动的 div。出于某种原因,这个 div 的内容拉伸(stretch)了我的页面并破坏了我的布局。我已将 main__listing 识别为有问题的 div。为了测试这是有问题的 div,我将宽度更改为 10%。它将 div 的内容缩小到您期望的荒谬大小,但我的页面仍然损坏。我曾经使用 Firefox 开发工具来查找以像素 (290px) 为单位的宽度。然后我将宽度设置为 290px。这修复了我的页面。我需要 div 是流畅的,所以这不是真正的解决方法,但我想知道这是为什么。

TL;DR 宽度设置为 % 的 div 与设置为相同大小(以像素为单位)的宽度不同。

CSS:

.main__listings {
  width: 100%;
}
.horizontal_scroll {
  display: flex;
  flex-wrap: nowrap;
  overflow-x: auto;
  overflow-y: hidden;
  -webkit-overflow-scrolling: touch;
}
.card {
  flex: 0 0 200px;
  margin: auto 10px;
}

HTML:

<div className="main__listings">
  <h1>Local Competitions</h1>
  <div className="horizontal_scroll">
    <div className="card">
      <h2>Competition Name</h2>
      <img src="http://via.placeholder.com/280x280" alt="" width="140" height="140"/>
    </div>
    <div className="card">
      <h2>Competition Name</h2>
      <img src="http://via.placeholder.com/280x280" alt="" width="140" height="140"/>
    </div>
    <div className="card">
      <h2>Competition Name</h2>
      <img src="http://via.placeholder.com/280x280" alt="" width="140" height="140"/>
    </div>
    <div className="card">
      <h2>Competition Name</h2>
      <img src="http://via.placeholder.com/280x280" alt="" width="140" height="140"/>
    </div>
    <div className="card">
      <h2>Competition Name</h2>
      <img src="http://via.placeholder.com/280x280" alt="" width="140" height="140"/>
    </div>
    <div className="card">
      <h2>Competition Name</h2>
      <img src="http://via.placeholder.com/280x280" alt="" width="140" height="140"/>
    </div>
    <div className="card">
      <h2>Competition Name</h2>
      <img src="http://via.placeholder.com/280x280" alt="" width="140" height="140"/>
    </div>
  </div>
</div>

最佳答案

百分比会根据您的屏幕尺寸而变化,其中像素不会根据屏幕而变化,并且像素不会响应不同的屏幕尺寸。

如果你想在不给出百分比的情况下给出一些值,你可以使用“rem”单位。而且它的响应速度更快。查看 rem 单位与像素相比如何工作。

https://www.sitepoint.com/understanding-and-using-rem-units-in-css/

已编辑 => 引用评论:

enter image description here

enter image description here

关于html - 为什么以百分比表示的宽度与以像素表示的宽度产生不同的结果?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48039618/

相关文章:

javascript - 在我的 morris.js 图表中,X 轴上的日期在月日日期之前添加数字 19

html - 加载时网站淡出

css - 移动显示 :Block link text to the bottom of a div

html - Flexbox 元素溢出到标题中

CSS 左右对齐文本

javascript - DIV 如何像 Javascript 中的另一个元素一样工作?

HTML/CSS - 如何使 div 相互适应

html - Flexbox - 显示 : flex - My contents appear in one line

html - 导航菜单幽灵

html - 如何在不损失质量的情况下将背景图像居中?