Guy Guy - 4 months ago 10
CSS Question

CSS: Getting a placeholder image take the entire size of the DIV without distortion

I want to place a png as a background image for a div that acts as a placeholder:
https://jsbin.com/hohegiyazu/edit?html,css,output

Code:

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
<style type="text/css" rel="stylesheet">

.container {
display: flex;
flex-direction: column;
}

.row {
display: flex;
flex-direction: row;
}

.placeholder {
background-image:url(/images/placeholder.png);
background-size:100% 100%;
height:50px;
flex:1;
}

</style>
</head>
<body>
<div class="container">

<div class="row">
<div class="placeholder"></div>
<div class="placeholder"></div>
</div>
<div class="row">
<div class="placeholder"></div>
<div class="placeholder"></div>
<div class="placeholder"></div>
<div class="placeholder"></div>
</div>

<div class="row">
<div class="placeholder"></div>
<div class="placeholder"></div>
<div class="placeholder"></div>
<div class="placeholder"></div>
<div class="placeholder"></div>
</div>
<div class="row">
<div class="placeholder"></div>
</div>
</div>
</body>
</html>


I get this effect:
svg example

The image is distorted according to the width of the element and the left and right margins are not equal.

I want to achieve this effect:
enter image description here

Is it possible?

Answer

The reason for this is that your PNG seem to include the white margins. So when you stretch it horizontally, the margins are proportionally stretched too and therefore become bigger.

I think you should use the border-image property as described here: https://css-tricks.com/understanding-border-image/

That way, you will be able to define which part of your image can be stretched and which part remains the same width/height, allowing you to keep corners and margins as you want them.

Comments