How to center an image?

本文介绍了三种在 div 中使图片居中的 CSS 方法,并详细解释了每种方法的具体实现方式。作者认为第三种方法更为优雅准确。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

I find three ways to center an image in a div:

<style type="text/css">
        .container1
        {
            border: solid 1px #666;
            width: 100px;
            height: 100px;
        }
        .container1 img
        {
            margin: 42px 0px 0px 42px; /* (100-16)/2 = 42 */
        }
        .container3
        {
            border: solid 1px #666;
            width: 100px;
            height: 100px;
            position: relative;
        }
        .container3 img
        {
            position: absolute;
            top: 42px;
            left: 42px; /* (100-16)/2 = 42 */
        }
        .container4
        {
            border: solid 1px #666;
            width: 100px;
            height: 100px;
            position: relative;
        }
        .container4 img
        {
            position: absolute;
            top: 50%;
            margin-top: -8px; /* 16/2 = 8 */
            left: 50%;
            margin-left: -8px;
        }
    </style>
    <div class="container1">
        <img src="mini/clock.gif" mce_src="mini/clock.gif" alt="" />
    </div>
    <br />
    <div class="container3">
        <img src="mini/clock.gif" mce_src="mini/clock.gif" alt="" />
    </div>
    <br />
    <div class="container4">
        <img src="mini/clock.gif" mce_src="mini/clock.gif" alt="" />
    </div>

In my opinion, the third method is graceful and accurate, which i borrow from my last example.

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值