我试图将一个div放置在另一个div的中间(水平和垂直),并将其缩放到最大,同时保持纵横比。
如果我进行缩放但保持顶部/左侧,那么它可以很好地工作,但是一旦我尝试将其居中,一切都会破裂。
#area是一个外部div,#cont是要缩放的主要内容div。在现实生活中,它内部有复杂的结构,而不仅仅是下面示例中的一个图像。
有jsfiddle示例显示了我的尝试。为了看到我的意思,请调整结果iframe的大小。
这里是保持div在左侧/顶部缩放的代码:https://jsfiddle.net/regc/3t4n3xud/1/
CSS
#area {
top: 40px;
bottom: 40px;
left: 10px;
right: 10px;
display: block;
position: absolute;
border: 4px solid #73AD21;
}
#cont {
width: 500px;
height: 200px;
position: absolute;
border: 4px solid #aa2221;
}
JS:
cont_el.style['transform'] = 'scale(' + scale + ')';
cont_el.style['transform-origin'] = 'left top';
cont_el.style.width = i.width * scale;
cont_el.style.height = i.height * scale;
这里是我尝试居中它的代码,但它会出错: https://jsfiddle.net/regc/4gcxcn7j/11/ CSS
#area {
top: 40px;
bottom: 40px;
left: 10px;
right: 10px;
display: block;
position: absolute;
border: 4px solid #73AD21;
}
#cont {
width: 500px;
height: 200px;
position: absolute;
border: 4px solid #aa2221;
margin: 0 auto;
top: 50%;
transform: translateY(-50%);
}
JS
cont_el.style['transform'] = 'scale(' + scale + ') translateY(-50%)';
cont_el.style['transform-origin'] = 'center center';
cont_el.style.width = i.width * scale;
cont_el.style.height = i.height * scale;
cont_el.style.margin = '0 auto';
cont_el.style.top = '50%';