几天来我一直在尝试使一个 position:fixed 元素居中,网上已经找到了很多解决方案,但由于效率低下或我自己经验不足,没有一个有效。
场景如下;我想做一个图像遮阳板,每当你点击一个图像时,一个固定的 div 就会变得可见,持有所述图像,这实际上是通过 JavaScript 完成的。 当我想将 div 居中时,无论您使用哪种分辨率,都会出现问题。
#galleryimage{
position:fixed;
z-index:200;
display:none;
max-height: 100%;
max-width: 100%;
}
#galleryimage img{
max-width:100%;
max-height:100%;
}
图片的宽高是未知变量,我对JS的处理经验不够,所以我想用纯CSS来做。但是,我永远无法让它居中。 边距不起作用,负边距的公式也不行,因为我不知道这些图像的宽度和高度变量。
有什么解决办法吗?
最佳答案
我会为此使用 JavaScript + jQuery,让生活更轻松。这是一个很好的起点:
<html>
<head>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script>
</head>
<style>
#galleryimage{
position:fixed;
z-index:200;
height: 100%;
width: 100%;
opacity: 0;
}
#galleryimage img{
position: absolute;
left: 50%;
top: 50%;
}
</style>
<body>
<div id="galleryimage">
<img src="" />
</div>
</body>
<script type="text/javascript">
$(document).ready(function(){
loadGalleryImage('your_image_name.jpg');
});
function loadGalleryImage(src){
$("#galleryimage img").on('load', function(){
$(this).css({marginTop: -($(this).height()/2), marginLeft: -($(this).width()/2)});
$("#galleryimage").animate({opacity:1}, 200);
$("#galleryimage img").off('load');
});
$("#galleryimage img").attr('src', src);
}
function hideGalleryImage(){
$("#galleryimage").animate({opacity:0}, 200);
}
</script>
</html>
这使用了一些技巧。在 CSS 中,图像绝对定位并放置在顶部和底部的 50% 点。然后,使用 jQuery,一旦我们知道图像已加载,我们就可以确定它的宽度和高度,并将其向左和向上移动这些值的一半。这会将它直接放在屏幕中央。为了美观,我在其中添加了一些动画内容 :)
关于css - 居中位置 :fixed div,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21891131/