Jordan Brown
Jordan Brown

Reputation: 439

Auto set image height and width based on image size

So I often export images from photoshop into PNG and into a webpage. I always have to manually type width: 100 height 100 and go up until I full reach the size of the image.

How can I automatically set the image height and width based on how big the image already is.

HTML

<div class="content">
    <div class="client">
        <div class="page">
            <div class="page_bg">
                <div class="welcome-card">
                    <div class="card">
                    </div>
                </div>
            </div>
        </div>
    </div>
</div>

CSS

.welcome-card{
    background-image:url("../images/welcome-card.png");
    height:400px;
    width:360px;
    border:1px solid red;
}

It looks like this https://i.gyazo.com/74c78f9cb79c195701d24ffb77abeec7.png

I keep adjusting the width and height until i fully reveal the image. Is there a faster way to do this??

Upvotes: 0

Views: 501

Answers (3)

Geuis
Geuis

Reputation: 42267

Use:

.welcome-card{
  background-image:url("../images/welcome-card.png");
  background-size: cover;
  background-position: center;
}

Note that you still need to set the height and width of the .welcome-card element to whatever you want the final size to be.

To make it more clear why this is important to know, I made this codepen: https://codepen.io/anon/pen/aGmMJz

Notice that the original image is 768x1024px. Using responsive layout, its easy to adjust the width and height of each cell without caring about the underlying dimensions of the background image just by using cover and background-position: center.

As you change the browser width, notice how everything moves around with no extra work needed. Most of your styling is at the smallest dimension and you just tweak certain properties as the width expands.

Upvotes: 1

Gustavo Chagas
Gustavo Chagas

Reputation: 359

try use this

object-fit: cover;

Upvotes: 0

Johannes
Johannes

Reputation: 67748

Just use an img tag instead of using the image as a background image in a div element

Upvotes: 1

Related Questions