css - 图片旋转放大居中
大家讲道理
大家讲道理 2017-04-17 13:03:58
[HTML讨论组]

屏幕中间有一个宽高未知的图片,点击旋转或放大按钮时,如何让图片始终在屏幕中间?
ps:代码如下,为什么还是不能居中,这有什么问题么?

<!doctype html>
<html>
<head>
    <meta charset="UTF-8">
    <title>Untitled Document</title>
    <style>
        *{padding:0; margin:0;}
        html,body{height:100%; position: relative;}
        img{border:0; vertical-align: middle;}
        #box{ position:absolute;} 
    </style>
    <script src="js/jquery-1.8.0.min.js"></script>
    <script>
        $(document).ready(function(){
            var width ='',
                height = '',
                src='images/123.jpg';
            $('#boxImg').attr('src',src);
            var img = new Image();
            img.src = src;
            img.onload = function(){
                width = img.width;
                height = img.height;
            };

            $('#box').css({
                'width':width+'px',
                'height':height+'px',
                'marginLeft':-width/2+'px',
                'marginTop':-height/2+'px',
                'top':50+'%',
                'left':50+'%'
            });
        });
     </script>
</head>
<body>
    <p id="box">
        <img id="boxImg" src="" alt="">
    </p>
</body>
</html>
大家讲道理
大家讲道理

光阴似箭催人老,日月如移越少年。

全部回复(3)
黄舟

css3 translate配合position absolute

巴扎黑

以前postion:absolute + 50% + 负margin的方式一样适用
只不过有css3可以把负margin改为translate(-50%,-50%)

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en">
<head>
    <meta http-equiv="Content-Type" content="text/html;charset=UTF-8" />
    <title></title>
    <style>
    body,html{
        height:100%;
    }
    #test{
        position:absolute;
        top: 50%;
        left: 50%;
        transform: translate(-50%,-50%);
    }
    #myimg{
        background-color:#f00;
        transform: scale(1.5);
    }
    </style>
</head>
<body>
    <p id="test">
        <p style="width:300px;height:200px" id="myimg">
    </p>
</body>
</html>
ringa_lee

动画,矩阵变换…改变中心点

热门教程
更多>
最新下载
更多>
网站特效
网站源码
网站素材
前端模板
关于我们 免责申明 意见反馈 讲师合作 广告合作 最新更新 English
php中文网:公益在线php培训,帮助PHP学习者快速成长!
关注服务号 技术交流群
PHP中文网订阅号
每天精选资源文章推送
PHP中文网APP
随时随地碎片化学习
PHP中文网抖音号
发现有趣的

Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号