css 单行图片文字水平垂直居中汇总

本文详细介绍了如何使用CSS实现图片和文本在网页布局中的水平和垂直居中,包括行内元素、块级元素的居中方法,以及利用flex布局和背景图片技术实现图片与文字的完美对齐。

 

(1) 水平居中

a. 行内元素水平居中

因为img是行内元素(行内块级元素也一样)父级元素设置text-align:center即可,例如:

<div style="width: 600px; height: 300px; border:1px solid red;text-align: center;" >
    <img src="static/images/banner.png" alt="" style="width: 200px; height: 200px;">
</div>

 

b. 块级元素水平居中

块级元素定宽后设置margin:0 auto(第一个数值视情况而定)即可,例如

<div style="width: 600px; height: 300px; border:1px solid red;" >
    <img src="static/images/banner.png" alt="" style="width: 200px; height: 200px; display: block; margin: 0 auto;">
</div>

 

(2) 垂直居中

  1. 作为背景图片定好宽高,设置background属性 ,例如

.bg-center{
    background:url('static/images/banner.png') no-repeat;
    background-size: 200px 200px;
    background-position: center center;
}

 

  1. 非背景图设置图片position:absolute; 设置left top 距离即可,例如

<div style="width: 600px; height: 600px; border:1px solid red; position: relative" >
    <img src="static/images/banner.png" alt="" style="width: 200px; height: 200px; position: absolute; left: 200px;top:200px;">
</div>

注:如果子元素绝对定位父级需要添加position:relative 样式。

 

 

(3) 图片文字垂直居中

  1. flex方式(要求支持flex) 例:

兼容性:https://blog.youkuaiyun.com/m0_37142141/article/details/79709747

<div style="width: 300px;height: 60px; border:1px solid red; display: flex;align-items: center;">
    <div style="flex:0 0 48px;border:1px solid green;font-size: 0;">
        <img src="static/images/banner.png" alt="" style="width: 48px;height: 48px; ">
    </div>
    <div style="flex: 1;border:1px solid green;">abc123我是</div>
</div>

效果图:

 

  1. 背景图片形式(推荐方式)

<div style="width: 300px;height: 60px; border:1px solid red; background: url('static/images/banner.png') no-repeat;background-size: 48px 48px; background-position: left center; padding-left: 48px; line-height: 60px;">
    abc123我是
</div>

效果图:

 

如果只有图片没有文字的话可以参照(2)中的方法,另外下面代码也可以实现

<div style="width: 300px;height: 60px; border:1px solid red;line-height: 60px; font-size: 0;">
    <img src="static/images/banner.png" alt="" style="width: 48px;height: 48px; vertical-align: middle;">
</div>

效果图:

 

好了到此结束。

转载于:https://www.cnblogs.com/cuiguoliang/p/9983588.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值