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

短命女 2023-10-02 18:17 69阅读 0赞

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

水平居中:

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

  1. img {
  2. display: block;
  3. margin: 0 auto;
  4. }

2.flex布局

  1. .box1 {
  2. width: 100px;
  3. height: 100px;
  4. background-color: aquamarine;
  5. display: flex;
  6. justify-content: center;
  7. }

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

  1. .box1 {
  2. width: 100px;
  3. height: 100px;
  4. background-color: aquamarine;
  5. text-align: center;
  6. }

4.定位

  1. img {
  2. width: 50px;
  3. height: 50px;
  4. position: relative;
  5. left: 50%;
  6. transform: translateX(-50%);
  7. }

垂直居中:

1.flex布局

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

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

2.display:table-cell

  1. .box1 {
  2. width: 100px;
  3. height: 100px;
  4. background-color: aquamarine;
  5. display: table-cell;
  6. vertical-align: middle;
  7. }

3.定位

  1. img {
  2. width: 50px;
  3. height: 50px;
  4. position: relative;
  5. top: 50%;
  6. transform: translateY(-50%);
  7. }

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

代码样例(example):

CSS:

  1. .container {
  2. width: 400px;
  3. height: 800px;
  4. background-color: aliceblue;
  5. display: flex;
  6. justify-content: center;
  7. align-items: center;
  8. margin: 0 auto;
  9. }
  10. .box1 {
  11. width: 200px;
  12. height: 200px;
  13. background-color: aquamarine;
  14. /* display: flex;
  15. align-items: center; */
  16. /* 对单行弹性盒子模型使用可以使用 */
  17. /* align-content: center; 通常使用该属性设置垂直居中,但是该属性对单行弹性盒子模型无效。(即:带有 flex-wrap: nowrap)。*/
  18. }
  19. .box1 img {
  20. width: 100px;
  21. height: 100px;
  22. position: relative;
  23. top: 50%;
  24. left: 50%;
  25. transform: translate(-50%, -50%);
  26. /* display: block;
  27. margin: 0,auto; */
  28. }

watermark_type_d3F5LXplbmhlaQ_shadow_50_text_Q1NETiBAR2F2aeabpg_size_20_color_FFFFFF_t_70_g_se_x_16

发表评论

表情:
评论列表 (有 0 条评论,69人围观)

还没有评论,来说两句吧...

相关阅读

    相关 水平垂直居中

    (1)水平居中: 元素为行内元素,设置父元素text-align:center 如果元素宽度固定,可以设置左右margin为auto 如果元素为绝对定位(或