【问题标题】:align-self:flex-end and margin-bottom: xpx not working as expected in Safari and iOS devicesalign-self:flex-end 和 margin-bottom: xpx 在 Safari 和 iOS 设备中无法正常工作
【发布时间】:2021-12-10 21:55:46
【问题描述】:

我在使用 iOS 时遇到了一些问题,忽略了 align-self:flex-endmargin-bottom: 8px 的组合。

在 Android 设备、带有 Chrome 和 Firefox 的各种 Windows 版本以及 macOS 上的 Chrome 上,#totalImg 显示为我所期望的 - 右下角,略微凸起。

在适用于 macOS 的 Safri 和适用于 iOS 的 Safari 和 Chrome 上,#totalImg 粘在底部。

查看下图了解当前行为:

我知道我可以通过应用 bottom: 8px 获得一致的跨浏览器行为,但这似乎仅在我的测试用例中有效,并且在生产中失败,具体取决于 Android 或 iOS 设备的屏幕宽度。例如,在 Android 版 Chrome 上,bottom: 8px#totalImages 最终可能位于其父级 div 的中间,或者远低于它。

    .image.big.j_launch {
      display: flex;
      display: -webkit-flex;
    }
    .image.big {
      width: auto;
      height: auto;
      max-width: 320px;
      margin-bottom: 10px;
      float: none;
      position: relative;
    }
    #totalImg {
      display: block;
      height: 15px;
      position: absolute;
      right: 11px;
      background-color: rgba(0, 0, 0, 0.35);
      padding: 2px 6px;
      border-radius: 3px;
      color: white;
      font-size: 11px;
      text-align: center;
      align-self: flex-end;
      margin-bottom: 8px;
    }
    <div class="image big j_launch" data-index="0">
      <div id="totalImg"><span>1 / 18</span></div>
      <img src="https://via.placeholder.com/320x240">
    </div>

如何获得一致的跨浏览器解决方案,将#totalImg 放置在当前放置在第一张图像中? Safari(和一般的 iOS)是否有理由忽略其他平台/浏览器上似乎正在运行的内容?

查看 Safari 中的文档检查器,我可以看到已应用边距 - 在 #totalImg 下方有一个橙色矩形,当我更改样式表中的 margin-bottom 值时,它会不断增长/向下延伸检查员。它只是没有像我预期的那样在视觉上应用。

【问题讨论】:

  • 不幸的是,我在 Safari 中遇到了类似的问题,忽略了广泛使用的 CSS 属性。

标签: css flexbox safari


【解决方案1】:

虽然这是一个解决方案,但不是最好的解决方案,我建议不要这样做,即使它有效。

首先,需要一点 JavaScript(见 this link)。

var b = document.documentElement;
b.setAttribute('data-useragent',  navigator.userAgent);
b.setAttribute('data-platform', navigator.platform );
b.className += ((!!('ontouchstart' in window) || !!('onmsgesturechange' in window))?' touch':'');

该块的作用是向文档本身添加两个数据属性(如果是手持设备,则添加一个touch 类)。在我的情况下 - iPhone 和 Mac - data-platform 的值分别为 iPhoneMacIntelclassnamedata-useragent 在此上下文中是不必要的,但出于说明目的并未从原始代码中删除。

接下来,为 CSS 添加一些新规则。

html[data-platform*='Mac'] #totalImg,
html[data-platform*='iPhone'] #totalImg {
  bottom: 8px !important;
  margin-bottom: unset !important;
}

这依赖于平台的部分处理,并相应地调整规则 - 因为bottom 被识别并应用于*OS 设备,而margin-bottom 未被识别,规则被更改。

我不喜欢这个的原因是它看起来像 Rube Goldberg machine,而且对于本应仅在 CSS 中解决的问题来说,它过于复杂。

更不用说它依赖于已弃用/过时的功能。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2014-04-05
    • 1970-01-01
    • 1970-01-01
    • 2021-10-04
    • 1970-01-01
    • 2017-11-04
    • 1970-01-01
    相关资源
    最近更新 更多