首页 > 解决方案 > align-self:flex-end 和 margin-bottom: xpx 在 Safari 和 iOS 设备中无法正常工作

问题描述

我在使用 iOS 时遇到了一些问题,忽略了align-self:flex-end和的组合margin-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样式表检查器中的值时,它会不断向下增长/扩展。它只是没有像我期望的那样在视觉上应用。

标签: cssflexboxsafari

解决方案


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

首先,需要一点 JavaScript(见此链接)。

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 机器,而且对于应该单独在 CSS 中解决的问题来说它过于复杂。

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


推荐阅读