![](/img/trans.png)
[英]Vertically and Horizontally Center Image inside a Div, if you don't know Image's Size?
[英]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.