当我在当前窗口中打开图像时,如何居中图像

How to center image, when i open it in current window

本文关键字:图像 何居中 窗口      更新时间:2023-09-26

我在图像居中方面有问题。我通过单击在当前窗口中打开图像,但它看起来是错误的..现在的样子

我应该如何解决它?这是我的 html 标记:

<div id="bgdiv"></div>
<img src="" onclick="expand(this);"... />

这是我的JS方法:

expand = function (a) {
var me = a.src;
$(a).after("<img src=" + me + " id='2rmv' />");
$('#2rmv').css({
    'position': 'absolute',
    'width': '500px !important',
    'height': '400px !important',
    'right': '1%',
    'z-index': '10001',
    'display': 'block',
    'border': '2px groove white',
    'border-radius': '10px'
});
$('#bgdiv').css({
    'background-color': 'black',
    'height': '100%',
    'text-align': 'center',
    'left': '0px',
    'opacity': '0.7',
    'position': 'fixed',
    'top': '0px',
    'width': '100%',
    'z-index': '10000'
});
$('#bgdiv').on('click', function () {
    $('#bgdiv').removeAttr("style");
    $('#2rmv').remove();
});
};

如果我添加"左"参数而不是"右",最后一个元素显示错误。

一个非常快速的谷歌搜索在 10 秒内给了我以下答案:

将以下 css 应用于您的图像div:

position: absolute;
top: 50%;
left: 50%;
margin-right: -50%;
transform: translate(-50%, -50%)