如何将TwentyTwenty.js 图像保持在中心?

Mar*_*rko 1 css jquery twentytwenty

我想使用TwentyTwenty.js代码来比较图像。除了图像与左侧对齐外,一切都很好。如何在不明确设置容器宽度的情况下将它们保持在中心?

<div id="beforeafter" class="twentytwenty-container">
  <img src="https://lorempixel.com/800/300/sports/2/">
  <img src="https://lorempixel.com/800/300/sports/3"/>
</div>

$(window).load(function() {
  $("#beforeafter").twentytwenty();
});
Run Code Online (Sandbox Code Playgroud)

http://codepen.io/anon/pen/EmEYjQ

如果我在容器上设置固定宽度,则图像位于中心,但我希望图像不受宽度限制,但它们不比屏幕宽

如果我使用 flex 居中,则手柄不在中心

  display: flex;
  justify-content: center;
Run Code Online (Sandbox Code Playgroud)

Lou*_*tte 5

我也过得很辛苦!
我花了很多时间研究所有我能找到的相关 CSS。

最后......这是一个简单的解决方案:

$(window).load(function() {
  // Was there.
  $("#beforeafter").twentytwenty();

  // Mesure your images and divide by 2.
  var imgWidth = $("#beforeafter img").width()/2;

  // On the container, apply a left offset of 50% (screen center) - minus half image width.
  $("#beforeafter").css({"position":"relative","left":"calc(50% - "+ imgWidth+ "px)"});
});
Run Code Online (Sandbox Code Playgroud)

代码笔