Search code examples
htmlcssvertical-alignment

Base percentage off height instead of width in css?


I have the following css in a page to always make my picture centered:

img {
        padding: calc(49% - 306px);
    }

The problem I have is that the "49%" is basing off the page width, and not height as I want. Is there a way I can change that? Thanks!

Note: My picture is in a <div align="center"> to center it horizontally


Solution

  • Without having full context of what you're trying to do, I'd guess CSS Flex is your best bet. The snippet I've attached shows you one method of centering an image inside a div when the image is not a full-sized background.

    Keep in mind that this solution will need to be re-worked a little for your application.

    .container {
      border:1px solid red;
      margin:0 auto;
      display:flex;
      height:500px;
      width:500px;
      justify-content:center;
      align-items:center;
    }     
    <div class="container">
    
      <img src="https://www.w3schools.com/howto/img_fjords.jpg" width="100px" height="100px">
      
    </div>