【问题标题】:Overlaying & Centering Two Images, using CSS使用 CSS 叠加和居中两个图像
【发布时间】:2012-01-28 05:12:16
【问题描述】:

我正在创建一个网站,需要两个图像相互叠加,顶部图像居中,但是我还需要整个块在页面中居中,所以我认为我不能使用绝对定位,因为我需要页面可以缩放。

我正在使用 -

img.center {   display: block;   margin-left: auto;   margin-right: auto; }

在页面上居中图像。

我不确定我是否已经很好地解释了这一点,所以希望下面的模型会有所帮助。

我已经查看了图像叠加,但它们似乎都使用绝对定位,我似乎无法使其工作,以便图像始终使用该方法居中。

有没有办法做到这一点?如果一些示例代码非常有用,或者只是朝着正确的方向发展。

谢谢。

【问题讨论】:

    标签: css image overlay center


    【解决方案1】:
    <div class="img_cont">
        <img src="1.png" alt="" class="first"/>
        <img src="2.png" alt="" class="second"/>
    </div>
    <style type="text/css">
        div {
            width: 300px;
            height: 300px;
            position: relative;
                margin: 0 auto;
        }
    
        .first {
            width: 100%;
            height: 100%;
        }
    
        .second {
            position: absolute;
        }
    </style>
    <script type="text/javascript">
        $(".home_click").css("left", ($(".img_cont").width() - $(".second").width()) / 2 + "px");
        $(".home_click").css("top", ($(".img_cont").height() - $(".second").height()) / 2 + "px");
    </script>
    

    【讨论】:

      【解决方案2】:

      您可以使用negative offset technique

      <div class="img_cont">
          <img src="1.png" alt="" class="first"/>
          <img src="2.png" alt="" class="second"/>
      </div>
      <style>
      .first, .second{
          margin:0 0 0 -200px; /* where 400px is width offset is / 2) */
          position:absolute;top:0;left:50%;
      }
      .second{
          margin:0 0 0 -100px; /* let's guess second image was 200px wide */
      }
      </style>
      

      【讨论】:

        【解决方案3】:

        <style type="text/css">
        	body {
          margin: 0px;
        }
        
        .height-100vh {
          height: 100vh;
        }
        
        .center-aligned {
          display: box;
          display: flex;
          box-align: center;
          align-items: center;
          box-pack: center;
          justify-content: center;
        }
        
        .background-image {
          position: relative;
        }
        
        .text {
          position: absolute;
        }
        </style>
        <div class="height-100vh center-aligned">
          <img class="background-image" src="http://i.imgur.com/1aBfM.png" />
          <img src="http://i.imgur.com/DH3Qw.png" class="text">
        </div>

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 2015-04-29
          • 1970-01-01
          • 1970-01-01
          • 2018-04-13
          • 1970-01-01
          • 2016-09-26
          • 1970-01-01
          • 1970-01-01
          相关资源
          最近更新 更多