关于照片(img)的水平居中和垂直居中

本文主要是讲述照片(img)的水平居中和垂直居中,但是其他元素的水平居中和垂直居中也可借鉴此文。

水平居中:

1.将img元素设置成块级元素

img {
            display: block;
            margin: 0 auto;
        }

2.flex布局

.box1 {
            width: 100px;
            height: 100px;
            background-color: aquamarine;
            display: flex;
            justify-content: center;
        }

3.父元素设置text-align:center

.box1 {
            width: 100px;
            height: 100px;
            background-color: aquamarine;
            text-align: center;
        }

4.定位

img {
            width: 50px;
            height: 50px;
            position: relative;
            left: 50%;
            transform: translateX(-50%);
        }

垂直居中:

1.flex布局

.box1 {
            width: 100px;
            height: 100px;
            background-color: aquamarine;
            display: flex;
            align-items: center;    /* 对单行弹性盒子模型使用可以使用 */
            /* align-content: center;  通常使用该属性设置垂直居中,但是该属性对单行弹性盒子模型无效。(即:带有 flex-wrap: nowrap ,或者盒子中本来就只有一个元素)。*/
        }

tip:CSS align-items属性将所有直接子节点上的align-self值设置为一个组。align-self属性设置项目在其包含块中在交叉轴方向上的对齐方式。

2.display:table-cell

.box1 {
            width: 100px;
            height: 100px;
            background-color: aquamarine;
            display: table-cell;
            vertical-align: middle;
        }

3.定位 

img {
            width: 50px;
            height: 50px;
            position: relative;
            top: 50%;
            transform: translateY(-50%);
        }

tip:通过设置line-height等于父元素高度可以使单行文字实现垂直居中。

代码样例(example):

CSS:

.container {
            width: 400px;
            height: 800px;
            background-color: aliceblue;
            display: flex;
            justify-content: center;
            align-items: center;
            margin: 0 auto;
        }
        
        .box1 {
            width: 200px;
            height: 200px;
            background-color: aquamarine;
            /* display: flex;
            align-items: center; */
            /* 对单行弹性盒子模型使用可以使用 */
            /* align-content: center;  通常使用该属性设置垂直居中,但是该属性对单行弹性盒子模型无效。(即:带有 flex-wrap: nowrap)。*/
        }
        
        .box1 img {
            width: 100px;
            height: 100px;
            position: relative;
            top: 50%;
            left: 50%;
            transform: translate(-50%, -50%);
            /* display: block;
            margin: 0,auto; */
        }

  • 8
    点赞
  • 24
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

Gavi曦

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值