繁体   English   中英

如何在较小的 div 内制作图像中心(垂直和水平)

[英]How to make an image center (vertically & horizontally) inside a smaller div

我有一个 1024 x 768 像素的 div。 我想在 div 的中间显示一个 1920 x 1080 px 的图像,并继续在滚动 div 时可见。

怎么做到呢?

这是测试代码。

 var el = document.querySelector('div.mainDiv'); var newWidth = Math.ceil($("#baseImg").width()/2); var newHeight = Math.ceil($("#baseImg").height()/2); el.scrollLeft = newWidth; el.scrollTop = newHeight;
 <!-- begin snippet: js hide: false console: true babel: false -->
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <div class="mainDiv"> <img id="baseImg" src="https://dummyimage.com/1920x1080/000/fff"> </div>

.mainDiv {
  margin: 0 auto;
  width: 1042px;
  height: 768px;
  overflow: scroll;
}

.mainDiv img {
  width: 1920px;
  height: 1080px;
}
<div class="mainDiv">
  <img src="https://dummyimage.com/1920x1080/000/fff">
</div>

- -编辑 - -

我用一些javascript代码解决了这个问题

        var el = document.querySelector(element);

        var newWidth = Math.ceil($(elementId).width()/2);
        var newHeight = Math.ceil($(elementId).height()/2);

        el.scrollLeft = newWidth;
        el.scrollTop = newHeight;

可能这会有所帮助。

 .container { position: relative; width: 200px; height: 200px; overflow: scroll; } .my-image { position: absolute; top: 50%; left: 50%; transform: translate(-50%, -50%); }
 <div class="container"> <img class="my-image" src="http://www.placehold.it/400x400" alt=""> </div>

您需要做的就是告诉图像它不能大于容器 div

<div id="div-one">
  <img src="http://lorempixel.com/400/400" alt="">
</div>

#div-one {max-width: 200px;}
#div-one img {max-width: 100%}

或者作为背景图片,你可以这样做

<div id="div-one">
  <p>some text</p>
</div>

#div-one {
  max-width: 200px;
  height: 200px;
  background: url("http://lorempixel.com/400/400");
  background-position: center;
  background-size: cover;
}

简单的解决方案

 div{display:flex;align-items:center;} img{ margin: auto; object-fit: cover; display: block; overflow:hidden}
 <div style="width:1024px;height:768px;border:1px solid blue"> <img src="https://dummyimage.com/1920x1080/000/fff"> </div>

你的 Css 应该是这样的,容器类(.container)具有固定的宽度和高度,在 x 和 y 上有一个溢出。 到中心添加一个 class(.centerDivWrapper) 。

.centerDivWrapper{
width:1024px;
height:768px;
margin-left:auto;
margin-right:auto;
}
.container{
width:1024px;
height:768px;
float:left;
position:absolute;
overflow-x:auto;
overflow-y:auto;
}
.imgclass{
height:auto;
float:left; 
}

你的 HTML 应该是这样的。 将 div 居中添加一个包装器(centerDivWrapper)。

<div class="centerDivWrapper">
<div class="container">
<img class="imgclass" alt="YourAltSrc" src="YourImageSource">
</div></div>

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM