-1

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

Milan1360
  • 11
  • 4
  • 2
    It's hard to determine the most effective method without more context. Can you create a [working example](https://stackoverflow.com/help/mcve) of your situation? You might consider [using flexbox](https://stackoverflow.com/questions/25832340/css-flexbox-vertically-horizontally-center-image-without-explicitely-defining-pa). – showdev Feb 14 '18 at 22:02
  • Percentage-based padding is the wrong approach for centering an element. [Maybe this article will help](https://css-tricks.com/snippets/css/absolute-center-vertical-horizontal-an-image/). – APAD1 Feb 14 '18 at 22:10
  • No, there's no way you can change calc percentage base value from width to height. – TylerH Feb 14 '18 at 22:19

3 Answers3

0

You could change the img element to a div and get the image as a background image like this:

div {
   width:100%; 
   height:100%; 
   background:url(logo.png) center center no-repeat;
 }
code-orange
  • 129
  • 6
0

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>
hypern00b
  • 340
  • 1
  • 10
0

Can you use flexbox?

html, body, div.center {margin: 0;height: 100%;}
div.center {display:flex; align-items: center;}

img {
  flex: 0 0 auto;
  margin: auto;
}
<div class="center">
  <img src="//placehold.it/306x100" alt="">
</div>

Demo: http://output.jsbin.com/xotupegove

Joseph Marikle
  • 76,418
  • 17
  • 112
  • 129