Jason
Jason

Reputation: 171

Setting linear gradient height AND width

I am aware that you can set the width of a linear gradient using

    .grey-block { background: linear-gradient(to right, #f9f9f9 0%, #f9f9f9 35%, white 35%, white 100%); }

As well as the height

    .grey-block { background: linear-gradient(to bottom, #f9f9f9 0%, #f9f9f9 65%, white 65%, white 100%); }

However, is there a way you can set BOTH the height and the width using a the same css line?

Upvotes: 2

Views: 9399

Answers (2)

thgaskell
thgaskell

Reputation: 13226

To clarify, the code in the question is not setting the height and width of the gradient. It's adjusting the color stops, which results in a grey rectangle.

In order to adjust the actual dimensions of the gradient, we need to use the background-size property (as well as background-repeat) to set the height and width of the gradient.

With background-size in control of the gradient's dimensions, we can rewrite the CSS to be as follows:

.grey-block {
  background-color: white;
  background-image: linear-gradient(#f9f9f9, #f9f9f9);
  background-size: 35% 65%;
  background-repeat: no-repeat;
}

What's happening is that we're defining a "gradient" of a solid color and confining it's size. The background-repeat is disabled so that it will only render a single grey block.

.grey-block {
  background-color: white;
  background-image: linear-gradient(#f9f9f9, #f9f9f9);
  background-size: 35% 65%;
  background-repeat: no-repeat;
}


/* non-relevant styles */
body {
  background-color: #222;
}
.grey-block {
  height: 200px;
  width: 200px;
}
<div class="grey-block"></div>

Upvotes: 3

JasonB
JasonB

Reputation: 6368

You can specify an angle. That should do the trick.

.grey-block { background: linear-gradient( 135deg, #f9f9f9 0%, #f9f9f9 65%, white 65%, white 100%); }

Upvotes: 1

Related Questions