我可以使用CSS将一个图像的一半与另一个重叠吗

Can I overlap exactly half of an image with another using CSS?

本文关键字:一半 图像 另一个 重叠 一个 CSS 可以使 我可以      更新时间:2023-09-26

我正试图使用另一个图像在CSS中正好重叠半个图像。问题是我希望图像的高度是(x=200px)。图像的宽度将取决于图像的纵横比。我还能写CSS吗?它会将调整大小的图像的一半与另一个图像重叠。

下面是一个代码,我在其中播放了重叠图像的位置。我可以让CSS为我做这件事吗?或者有什么js可以帮助你?在下面的代码中,我希望高度保持不变,但使用的任何图像的一半都应该在宽度方向上重叠。

<html>
    <head>
        <style type="text/css">
            #collage-container{
                width:300px;
                height: 200px;
                position: relative;
                background:#f22;
            }
            #collage-one, #collage-two{
                height:200px;
                position:absolute;
            }
            #collage-one{
                z-index:1;
                left:100px;
                position:absolute;
            }
        </style>
    </head>
    <body>
        <div id=collage-container>
            <img src="http://www.hack4fun.org/h4f/sites/default/files/bindump/lena.bmp" id=collage-one />
            <img src="http://www.hack4fun.org/h4f/sites/default/files/bindump/lena.bmp" id=collage-two />
        </div>
    </body>
</html>

由于图像的width是不同的,您可以使用带有百分比值的CSS变换translate()表达式将图像移动到相对于其width值的一侧:

此处示例

#collage-container {
  height: 200px;
  position: relative;
}
#collage-container img {
  height: 100%; /* As tall as the container */
  width: auto;
  float: left;
}
#collage-container img + img {  /* Move the second image 50% of its width */
  transform: translateX(-50%);  /*  to the left */
}

值得注意的是,IE9+

中支持CSS转换

我认为,这很简单:

<html>
<head>
<style type=text/css>
  .container {
    float:left;
  }
  .half-img {
    display:inline-block;
    width:25%;
  } 
  .clear {clear:left;}
</style>
</head>
<body>
<div class="container">
  <span class="half-img">
    <img src="http://www.hack4fun.org/h4f/sites/default/files/bindump/lena.bmp" width="100">
  </span><img src="http://www.hack4fun.org/h4f/sites/default/files/bindump/lena.bmp" width="100">
</div>
<div class="clear"></div>
</body>
</html>