1. 程式人生 > 實用技巧 >面試:div水平垂直居中方案--img自適應

面試:div水平垂直居中方案--img自適應

<!DOCTYPE html>
<html>
    <head>
        <meta charset="utf-8">
        <title>垂直居中--圖片自適應寬高</title>
        <style type="text/css">
            /* 方法一 定位 為了看效果就加上了背景 寬高*/ 
            .wrap{
                position: relative;
                width: 200px;
                height
: 200px; background: #000; } .box{ position: absolute; top: 50%; left: 50%; background: #999; width: 100px; height: 100px; transform: translate(-50%,-50%); }
/* 方法二 flex佈局 */ .wrap{ display: flex; justify-content: center; align-items: center; width: 200px; height: 200px; background: #000; } .box{ background
: #999; width: 100px; height: 100px; } /* 圖片自適應寬高 */ img{ max-width: 100%; max-height: 100%; } </style> </head> <body> <div class="wrap"> <div class="box"> <img src="https://f11.baidu.com/it/u1=2936607031&u2=3595029289&fm=76" > </div> </div> </body> </html>