簡體   English   中英

"如何用css3繪制梯形\/梯形?"

[英]How to draw a trapezium/trapezoid with css3?

當您使用 Mobile Safari 訪問頁面http:\/\/m.google.com<\/a>時,您將看到頁面頂部的漂亮欄。

我想畫一些這樣的梯形(美國:梯形),但我不知道怎么畫。 我應該使用 css3 3d 變換嗎? 如果您有實現它的好方法,請告訴我。

由於這現在已經很老了,我覺得它可以與一些新技術一起使用一些新的更新答案。

CSS 轉換視角

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

SVG

 <svg viewBox="0 0 20 20" width="20%"> <path d="M3,0 L17,0 L20,20 L0,20z" fill="red" /> </svg>

帆布

 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();
 <canvas id="myCanvas" width="200" height="200"></canvas>

你可以像這樣使用一些 CSS:

 #trapezoid { border-bottom: 100px solid red; border-left: 50px solid transparent; border-right: 50px solid transparent; height: 0; width: 100px; }
 <div id="trapezoid"></div>

制作所有這些形狀真的很酷,看看更多漂亮的形狀:

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

編輯:此 css 應用於 DIV 元素

您有幾種選擇。 您可以簡單地使用圖像,使用 svg 繪制某些內容或使用 css 轉換扭曲常規 div。 圖像將是最簡單的,並且適用於所有瀏覽器。 在 svg 中繪制有點復雜,並且不能保證全面工作。

另一方面,使用 css 轉換意味着您必須在背景中放置形狀 div,然后將實際文本放在另一個元素中的它們上,以使文本也不會傾斜。 同樣,不能保證瀏覽器支持。

簡單的方法

要繪制任何形狀,您可以使用如下所示的 CSS clip-path屬性。

您可以使用免費的在線編輯器來生成此代碼(例如: https : //bennettfeely.com/clippy/

.trapezoid {
    clip-path: polygon(0 0, 100% 0, 84% 41%, 16% 41%);
}

帶有可重用代碼

如果你想讓它更具適應性,你可以定義一個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;
}

然后像這樣將它用於所需的元素(這里的參數是 $top-width, $bottom-width, $height):

.my-div {
    @include trapezoid(8rem, 6rem, 2rem);
}

這是一個老問題......但我想添加一個尚未提及的方法。 可以用半色半透明的漸變繪制三角形,然后可以從 3 個漸變形狀構建梯形。 這是一個示例代碼,3 個塊用不同的顏色繪制以便更好地理解:

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM