如何使用CSS将图像响应分为两个div块? [英] How to split an image responsive into two div blocks using css?

查看:42
本文介绍了如何使用CSS将图像响应分为两个div块?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的图像反应灵敏:

<img class="img-responsive" src="img/image.jpg"/>

我想将其分为两个div:

I want to split it into two divs :

<div class="slice s1"></div>
<div class="slice s2"></div>

或:

<div class="slice s1">
   <div class="slice s2"></div>
</div>

我该如何动态地或使用CSS做到这一点?

How can I do that dynamically or using css?

我尝试设置两个div的 background-image background-position ,但是新图像不是同样,它不再响应.

I tried to do it setting the background-image and the background-position of the two div, but the new image is not the same, it's no longer responsive.

推荐答案

我发现了一个受@wlh回答启发的解决方案:

I've found a solution inspired from @wlh 's answer :

.img-responsive{
  width: 100%;
  max-width: 100%;
  height: auto;
}
.hidden {
  visibility:hidden;
}
.sliced-img {
  position: relative;
  width: 100%;
}
.slice {
  position: absolute;
  top: 0;
  width: 50%;
  height: 100%;
  background-size: cover;
}

.s1 {
  left: 0;
  background-image: url('https://placehold.it/200/0e0e0e'); /* black */
  background-position: 0%;
}

.s2 {
  left: 50%;
  background-image: url('https://placehold.it/200/e8117f'); /* pink */
  background-position: -100%;
}

<!DOCTYPE html>
<html>
  <head>
    <meta charset="utf-8">
    <title></title>
    <link href="style.css" rel="stylesheet"/>
  </head>
  <body>
  <div class="sliced-img">
    <img src='https://placehold.it/200x200' class='img-responsive hidden'> <!-- This hidden image (image we want to slice) is under the two divs, it's just used to get the image height and/or the image src dynamically -->
    <div class="slice s1"></div>
    <div class="slice s2"> </div>
  </div> 
 </body>
</html>

注意

css background-image 属性将使用 jQuery .css()函数动态设置示例(不要忘记从 css 文件中的 .s1 .s2 中删除 background-image ):

The css background-image property will be set dynamically using the jQuery .css() function for example ( Don't forget to delete the background-image from .s1 and .s2 in the css file ) :

$( document ).ready(function() {
  var imageSrc = $('.sliced-img').children( 'img' ).attr( 'src' );
  $('.sliced-img').css("background-image","url('"+imageSrc+"')");
});

这篇关于如何使用CSS将图像响应分为两个div块?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆