Jacob Frye
Jacob Frye

Reputation: 55

How to create a trapezium shape using svg?

I wish to draw an upside-down spotlight for my web page. I would add some helpful code here but there isn't any and I have exhausted the entirety of internet to find anything helpful. I'm still learning HTML and CSS, so any suggestion in these areas would be nice. Also, I understand that a common way of creating a trapezium is using 'border-bottom/left/right' property but the problem there is that I can't fill the shape that forms with a gradient. So, any assistance on how to create a trapezium like this: \_/ would be quite helpful.

Upvotes: 1

Views: 3457

Answers (2)

Paul LeBeau
Paul LeBeau

Reputation: 101908

I'd argue that SVG is easier. But judge for yourself. Here is the equivalent SVG to the div/CSS version.

.trapezium {
  width: 30vmin;
}
<svg viewBox="0 0 30 20" class="trapezium">
  <defs>
    <linearGradient id="grad" x2="0" y2="1">
      <stop offset="0%" stop-color="red"/>
      <stop offset="25%" stop-color="orange"/>
      <stop offset="50%" stop-color="yellow"/>
      <stop offset="75%" stop-color="blue"/>
      <stop offset="100%" stop-color="green"/>
    </linearGradient>
  </defs>
  
  <polygon points="0,0, 30,0, 24,20, 6,20" fill="url(#grad)"/>
</svg>

Upvotes: 1

A Haworth
A Haworth

Reputation: 36590

One way to create a trapezium without an svg is to use CSS clip-path with the path being defined as a polygon. The points of the polygon can be set as % values so the element can be made responsive.

This CSS

.trapezium {
  width: 30vmin;
  height: 20vmin;
  background-image: linear-gradient(red, orange, yellow, blue, green);
  clip-path: polygon(0 0, 100% 0, 80% 100%, 20% 100%);
}

gives this:

enter image description here

.trapezium {
  width: 30vmin;
  height: 20vmin;
  background-image: linear-gradient(red, orange, yellow, blue, green);
  clip-path: polygon(0 0, 100% 0, 80% 100%, 20% 100%);
}
<div class="trapezium"></div>

You can use a similar technique if it has to be an SVG rather than achieved through plain CSS/HTML. See https://developer.mozilla.org/en-US/docs/Web/SVG/Element/polygon which describes how to use a polygon as an SVG path.

Upvotes: 3

Related Questions