gpt4 book ai didi

jquery - 使用 CSS 而不是 jquery 在 div 中居中图像

转载 作者:行者123 更新时间:2023-11-28 08:41:00 25 4
gpt4 key购买 nike

我正在尝试将任何大小的图像放入(始终)方形的 div 中,并在父 div 的大小发生变化时保留纵横比。这是我正在做的:

CSS:

.photo_container {
width: 250px;
height: 250px;
overflow: hidden;
border-style: solid;
border-color: green;
float:left;
margin-right:10px;
position: relative;
}

.photo_container a img{
position:absolute;
}

HTML

<!--p>Photo's height>width </p-->
<div class="photo_container">
<a href="#">
<img class="photo" src="https://upload.wikimedia.org/wikipedia/commons/thumb/5/57/ECurtis.jpg/224px-ECurtis.jpg"
style="width:100%; height:auto;">
</img>
</a>
</div>

<!--p>Photo's width>height </p-->
<div class="photo_container">
<a href="#">
<img class="photo" src="https://upload.wikimedia.org/wikipedia/commons/thumb/c/c8/Altja_j%C3%B5gi_Lahemaal.jpg/220px-Altja_j%C3%B5gi_Lahemaal.jpg"
style="width:auto; height:100%;left=-100px">
</img>
</a>
</div>

Javascript:

// fix image size on load
$(".photo").one("load", function() {
fixImage($(this));
}).each(function() {
if(this.complete) $(this).load();
});

// Just to test if everything's working fine
$(".photo").on("click",function(){
var rand = Math.floor(Math.random() * 200) + 80;
$(this).parent().parent().width(rand);
$(this).parent().parent().height(rand);
fixImage($(this));
});

// Brings the photo dead center
function fixImage(obj){
//alert("something changed");
var pw = obj.parent().parent().width();
var ph = obj.parent().parent().height();
var w = obj.width();
var h = obj.height();
console.log(w+" "+pw);
if(h>w){
var top = (h-ph)/2;
obj.css("top",top*-1);
}else{
var left = (w-pw)/2;
obj.css("left",left*-1);
}

}

工作示例: http://jsfiddle.net/vL95x81o/4

如何在不使用 jquery 而只使用 CSS 的情况下做到这一点?如果 div 的大小永远不变,这个解决方案就可以了。但我正在研究响应式设计,似乎 photo_container div 的大小可能需要根据屏幕大小更改(通过 CSS)。

裁剪前的照片如下:

Portrait Image Landscape Image

最佳答案

你可以这样做:

http://jsfiddle.net/vL95x81o/5/

<!--p>Photo's height>width </p-->
<div class="photo_container">
<div class="photo photo--1">
</div>
</div>

<!--p>Photo's width>height </p-->
<div class="photo_container">
<div class="photo photo--2">
</div>
</div>

.photo_container {
width: 250px;
height: 250px;
overflow: hidden;
border-style: solid;
border-color: green;
float:left;
margin-right:10px;
position: relative;
}

.photo {
height: 100%;
width: 100%;
}

.photo--1 {
background: url('https://upload.wikimedia.org/wikipedia/commons/thumb/5/57/ECurtis.jpg/224px-ECurtis.jpg') no-repeat center center;
background-size: cover;
}

.photo--2 {
background: url('https://upload.wikimedia.org/wikipedia/commons/thumb/c/c8/Altja_j%C3%B5gi_Lahemaal.jpg/220px-Altja_j%C3%B5gi_Lahemaal.jpg') no-repeat center center;
background-size: cover;
}

我已将 imgs 更改为带有背景图像的 div,并使用背景位置覆盖图像居中。

关于jquery - 使用 CSS 而不是 jquery 在 div 中居中图像,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32765527/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com