如何在响应式布局上将元素浮动到图像上?

时间:2015-12-22 16:31:24

标签: html css image responsive-design

以下是代码:

HTML:

<html>
    <head>
        <title>Sample Title</title>
        <link rel="stylesheet" type="text/css" href="style.css"/>
        <meta name="viewport" content="width=device-width">
    </head>
    <body>
        <div id="container">
            <img id="image" src="http://blog.clove.co.uk/wp-content/uploads/2013/01/Motorola_Razr_HD_Cam_Sample%20(7).jpg">
            <img id="arrow_left" src="http://iconizer.net/files/WPZOOM_Developer_Icon_Set/orig/arrow-left.png">
            <img id="arrow_right" src="http://iconizer.net/files/WPZOOM_Developer_Icon_Set/orig/arrow-right.png">
        </div>
    </body>
</html>

CSS:

#container {
    position: fixed;
    margin: auto;
    top: 0;
    left: 0;
    right: 0;
    bottom: 0;
    width: 90%;
    height: 90%;
    background-color: silver;
    text-align: center;
}

#image {
    position: relative;
    top: 50%;
    transform: translateY(-50%);
    max-width: 100%;
    max-height: 100%;
}

#arrow_left {
    width: 50px;
    position: absolute;
    top: 50%;
    transform: translateY(-50%);
    left: 0;
    z-index: 1000;
}

#arrow_right {
    width: 50px;
    position: absolute;
    top: 50%;
    transform: translateY(-50%);
    right: 0;
    z-index: 1000;
}

我要做的是将箭头图像浮动到图像的左侧和右侧,图像的中间位置。我不希望箭头在图像之外。

您会注意到,如果您将此布局调整为横向,则图像与左侧和右侧容器的外边框之间会有间隙。箭头浮动在图像之外。我需要阻止这种情况发生。

- 我再次更新了代码。 X)

1 个答案:

答案 0 :(得分:1)

如果可以接受,可以通过添加一点jQuery来实现:)

以下是代码:

HTML

<div id="container">
  <img id="image" src="http://blog.clove.co.uk/wp-content/uploads/2013/01/Motorola_Razr_HD_Cam_Sample%20(7).jpg">
  <div class="controls">
    <img id="arrow_left" src="http://iconizer.net/files/WPZOOM_Developer_Icon_Set/orig/arrow-left.png">
    <img id="arrow_right" src="http://iconizer.net/files/WPZOOM_Developer_Icon_Set/orig/arrow-right.png">
  </div>
</div>

<强> CSS

#container {
  position: fixed;
  margin: auto;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  width: 90%;
  height: 90%;
  background-color: silver;
  text-align: center;
}

#image {
  position: relative;
  top: 50%;
  transform: translateY(-50%);
  max-width: 100%;
  max-height: 100%;
}

.controls {
  position: absolute;
  left: 50%;
  top: 50%;
  margin-top: -30px
}

#arrow_left {
  width: 50px;
  float: left;
}

#arrow_right {
  width: 50px;
  float: right;
}

<强> JQUERY

var img_w = $('#image').width();
$('.controls').css({
  'width': img_w,
  'margin-left': '-' + (img_w / 2) + 'px'
});
$(window).resize(function() {
  var img_w = $('#image').width();
  $('.controls').css({
    'width': img_w,
    'margin-left': '-' + (img_w / 2) + 'px'
  });
});

JS小提琴链接: https://jsfiddle.net/omerblink/d6q9uoe3/

如果您在评论中需要更多帮助,请与我们联系......