首页 > 关于未知大小元素居中

关于未知大小元素居中

向各位大神请教如下代码如何使图片居中,不要用上具体的px大小:

<!DOCTYPE html>
<html>

<head>
    <meta charset="utf-8">
    <title>text</title>
    <style>
        a {position:absolute;left:50%;top:50%;float:left;}
        img {position:relative;left:-50%;top:-50%;display: block;}
    </style>
</head>
<body >
    
    <div id = "div" style = "width:300px;height:300px;background-color:red;border-radius:50%;position:relative;">
        <a > <img src = "banner.png" style = "width:100px" id = "a1"></a>
    </div>
    <script>
    /*var a = document.getElementById("div");
    alert(a);
    alert(window.getComputedStyle(a, null).height);
    */
    </script>
</body>

</html>


<html>
    <head>
        <meta charset="utf-8">
        <title>text</title>
        <style>
            div{display: table;}
            a {
                display: table-cell;
                text-align: center;
                vertical-align: middle;
            }
            img {vertical-align: middle;}
        </style>
    </head>
<body >
    
    <div id = "div" style = "width:300px;height:300px;background-color:red;border-radius:50%;position:relative;">
        <a > <img src = "http://nos.netease.com/edu-image/B33C92197127CC433CCAF71849874EC3.jpg" id = "a1"></a>
    </div>
    <script>
    /*var a = document.getElementById("div");
    alert(a);
    alert(window.getComputedStyle(a, null).height);
    */
    </script>
</body>
</html>

使用table布局很简单啊


如果不考虑兼容

 <!DOCTYPE html>
<html>

<head>
    <meta charset="utf-8">
    <title>text</title>
    <style>
        #div a{
            position:absolute;
            left:50%;
            top:50%;
            transform:translate(-50%,-50%);
        }
    </style>
</head>
<body >
    <div id = "div" >
        <a> <img src = "banner.png" style = "width:100px" id = "a1"></a>
    </div>
</body>
</html>

或者改成这样?

 <!DOCTYPE html>
<html>

<head>
    <meta charset="utf-8">
    <title>text</title>
    <style>
        #div{
            display:table;
            width:300px;
            height:300px;
            background-color:red;
            border-radius:50%;
            position:relative;
        }
    
        #div a{
            display:table-cell;
            vertical-align:middle;
            text-align:center;
        }
    </style>
</head>
<body >
    <div id = "div" >
        <a> <img src = "banner.png" style = "width:100px" id = "a1"></a>
    </div>
</body>
</html>

试试在img里面使用 transform: translateX(-50%) translateY(-50%) 来代替。

【热门文章】
【热门文章】