Center image using text-align center?

后端 未结 24 1608
终归单人心
终归单人心 2020-11-21 17:53

Is the property text-align: center; a good way to center an image using CSS?

img {
    text-align: center;
}
24条回答
  •  情书的邮戳
    2020-11-21 18:40

    There are three methods for centering an element that I can suggest:

    1. Using the text-align property

          .parent {
          text-align: center;
      }
          

    2. Using the margin property

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

    3. Using the position property

      img {
          display: block;
          position: relative;
          left: -50%;
      }
      .parent {
          position: absolute;
          left: 50%;
      }


    The first and second methods only work if the parent is at least as wide as the image. When the image is wider than its parent, the image will not stay centered!!!

    But: The third method is a good way for that!

    Here's an example:

    img {
        display: block;
        position: relative;
        left: -50%;
    }
    .parent {
        position: absolute;
        left: 50%;
    }

提交回复
热议问题