如何用css3绘制梯形/梯形?

Cas*_*李秉骏 28 css html5 css3 css-shapes

当您使用Mobile Safari 转到http://m.google.com页面时,您会在页面顶部看到漂亮的栏.

我想画一些梯形(美国:梯形),但我不知道如何.我应该使用css3三维变换吗?如果你有一个很好的方法来实现它,请告诉我.

ElH*_*ker 49

你可以像这样使用一些CSS:

#trapezoid {
    border-bottom: 100px solid red;
    border-left: 50px solid transparent;
    border-right: 50px solid transparent;
    height: 0;
    width: 100px;
}
Run Code Online (Sandbox Code Playgroud)
<div id="trapezoid"></div>
Run Code Online (Sandbox Code Playgroud)

制作所有这些形状真的很酷,看看更好的形状:

http://css-tricks.com/examples/ShapesOfCSS/

编辑:此css应用于DIV元素


Ste*_*ide 47

由于现在已经很老了,我觉得它可以用一些新技术的新的更新答案.

CSS转换视角

.trapezoid {
  width: 200px;
  height: 200px;
  background: red;
  transform: perspective(10px) rotateX(1deg);
  margin: 50px;
}
Run Code Online (Sandbox Code Playgroud)
<div class="trapezoid"></div>
Run Code Online (Sandbox Code Playgroud)

SVG

<svg viewBox="0 0 20 20" width="20%">
  <path d="M3,0 L17,0 L20,20 L0,20z" fill="red" />
</svg>
Run Code Online (Sandbox Code Playgroud)

帆布

var c = document.getElementById("myCanvas");
var ctx = c.getContext("2d");
ctx.moveTo(30, 0);
ctx.lineTo(170, 0);
ctx.lineTo(200, 200);
ctx.lineTo(0, 200);
ctx.fillStyle = "#FF0000";
ctx.fill();
Run Code Online (Sandbox Code Playgroud)
<canvas id="myCanvas" width="200" height="200"></canvas>
Run Code Online (Sandbox Code Playgroud)

  • 第一部分应该是最佳答案 (2认同)
  • 我喜欢接受的答案,但在我使用关键帧`animation`的这个INSIDE的地方,我不得不使用包含在这个答案中的css`transform` (2认同)

Ski*_*lyx 9

简单的方法

要绘制任何形状,您可以使用 CSS Clip-path属性,如下所示。

您可以使用免费的在线编辑器来生成此代码(例如:https://bennettfeely.com/clippy/

.trapezoid {
    clip-path: polygon(0 0, 100% 0, 84% 41%, 16% 41%);
}
Run Code Online (Sandbox Code Playgroud)

具有可重用的代码

如果你想让它更具适应性,你可以定义一个Sass mixin,如下所示:

@mixin trapezoid ($top-width, $bottom-width, $height) {
    $width: max($top-width, $bottom-width);
    $half-width-diff: abs($top-width - $bottom-width) / 2;

    $top-left-x: 0;
    $top-right-x: 0;
    $bottom-left-x: 0;
    $bottom-right-x: 0;

    @if ($top-width > $bottom-width) {
        $top-left-x: 0;
        $top-right-x: $top-width;
        $bottom-left-x: $half-width-diff;
        $bottom-right-x: $top-width - $half-width-diff;
    } @else {
        $top-left-x: $half-width-diff;
        $top-right-x: $bottom-width - $half-width-diff;
        $bottom-left-x: 0;
        $bottom-right-x: $bottom-width;
    }

    clip-path: polygon($top-left-x 0, $top-right-x 0, $bottom-right-x $height, $bottom-left-x $height);
    
    width: $width;
    height: $height;
}
Run Code Online (Sandbox Code Playgroud)

然后将其用于所需的元素,如下所示(此处参数为 $top-width、$bottom-width、$height):

.my-div {
    @include trapezoid(8rem, 6rem, 2rem);
}
Run Code Online (Sandbox Code Playgroud)