Setting linear gradient height AND width

好久不见. 提交于 2021-02-17 06:10:11

问题


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?


回答1:


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>



回答2:


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

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


来源:https://stackoverflow.com/questions/48088159/setting-linear-gradient-height-and-width

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!