Home > Enterprise >  How to stretch background image to container width but retain original height?
How to stretch background image to container width but retain original height?

Time:07-11

I'm trying to put a background-image that should repeat vertically and stretch horizontally, but keep its height as original svg.

I've tried to fix the background-size: 100% 33px; but the orignal height is not retained.

Height should be the same in all .child and it should be stretched to its parent container.

Below are my try

  background-size: 100% 33px;  // TO FIX SIZE
  background-repeat: repeat-y; // REPEAT ONLY THROUGH Y

CODESANDBOX LINK FOR TRY

* {
  padding: 0;
  margin: 0;
  box-sizing: border-box;
}

div {
  border: 5px solid indianred;
}

.parent {
  height: 100vh;
  background-color: grey;
  display: flex;
}

div.child {
  background-image: url("https://assets-marvin.leadsquared.com/smartviews/images/column.svg");
}

.child:nth-child(1) {
  flex: 1;
}

.child:nth-child(2) {
  flex: 2;
  background-size: 100% 33px;
  background-repeat: repeat-y;
}

.child:nth-child(3) {
  flex: 3;
  background-size: 100%;
}
<div >
  <div ></div>
  <div ></div>
  <div ></div>
</div>

CodePudding user response:

You need to edit the SVG and add preserveAspectRatio="none"

* {
  padding: 0;
  margin: 0;
  box-sizing: border-box;
}

div {
  border: 5px solid indianred;
}

.parent {
  height: 100vh;
  background-color: grey;
  display: flex;
}

div.child {
  background-image: url('data:image/svg xml;utf8,<svg xmlns="http://www.w3.org/2000/svg" width="200" height="32.5" viewBox="0 0 200 32.5" preserveAspectRatio="none"><g id="Group_15" data-name="Group 15" transform="translate(10981 1350)"><g id="Group_11" data-name="Group 11" transform="translate(-10981 -1350)"><rect id="Rectangle_43" data-name="Rectangle 43" width="200" height="31.5" fill="#fff"/><rect id="Rectangle_44" data-name="Rectangle 44" width="176" height="20" rx="1" transform="translate(12 5.897)" fill="#f2f2f2"/></g><line id="Line_1" data-name="Line 1" x2="200" transform="translate(-10981 -1318)" fill="none" stroke="#ccd3da" stroke-width="1"/></g></svg>');
  background-size: 100% 33px;
  background-repeat: repeat-y;
}

.child:nth-child(1) {
  flex: 1;
}

.child:nth-child(2) {
  flex: 2;
}

.child:nth-child(3) {
  flex: 3;
}
<div >
  <div ></div>
  <div ></div>
  <div ></div>
</div>

  • Related