How to keep an image centered and responsive?

前端 未结 7 1202
没有蜡笔的小新
没有蜡笔的小新 2021-01-02 18:08

I have an image, centered both, horizontally and vertically

#logo01{
    position:absolute;
    top:50%;
    left:50%;
    margin-top:-146px;  // half of hei         


        
7条回答
  •  清酒与你
    2021-01-02 18:28

    Since most modern browsers support CSS grid now, I used CSS grid. I know this is an old post but for anyone in the future that doesn't know about CSS grid you should look into it, it's very helpful.

    Anyway, here's my solution:

    Create a div around the image and give it a class name so your HTML looks like this:

    Then in your CSS add this:

    .center-image {
      display: grid;
      justify-items: center;
    }
    

    Your image should be centered (horizontally). If you want it centered vertically too just add:

    align-items: center;
    

    to your div styling like this:

    .center-image {
      display: grid;
      justify-items: center;
      align-items: center;
    }
    

提交回复
热议问题