Có một cách hack CSS khá phổ biến bằng cách sử dụng các đường viền trong suốt trên phần tử 0-width / 0-height để bắt chước hình tam giác. Có một đoạn CSS ở đây trên CSS-Tricks mô tả nó.
Nếu, giống như tôi, bạn không bao giờ nhớ rõ nó hoạt động như thế nào, hãy chắc chắn rằng chúng tôi có thể sử dụng Sass để giúp chúng tôi.
/// Triangle helper mixin /// @param (Direction) $direction - Triangle direction, either `top`, `right`, `bottom` or `left` /// @param (Color) $color (currentcolor) - Triangle color /// @param (Length) $size (1em) - Triangle size @mixin triangle($direction, $color: currentcolor, $size: 1em) ( @if not index(top right bottom left, $direction) ( @error "Direction must be either `top`, `right`, `bottom` or `left`."; ) width: 0; height: 0; content: ''; z-index: 2; border-#(opposite-position($direction)): ($size * 1.5) solid $color; $perpendicular-borders: $size solid transparent; @if $direction == top or $direction == bottom ( border-left: $perpendicular-borders; border-right: $perpendicular-borders; ) @else if $direction == right or $direction == left ( border-bottom: $perpendicular-borders; border-top: $perpendicular-borders; ) )
Ghi chú bổ sung:
* opposite-position
Chức năng đến từ La bàn; nếu bạn không sử dụng La bàn, bạn có thể cần phải có La bàn của riêng mình;
* Mixin không liên quan đến việc định vị tam giác; nó hoàn toàn tốt để kết hợp nó với một hỗn hợp định vị;
* Lệnh content
này có nghĩa là cho phép nó được sử dụng trên các phần tử giả, mà thực tế là hầu hết các trường hợp.
Sử dụng
.foo::before ( @include triangle(bottom); position: absolute; left: 50%; bottom: 100%; )
.foo::before ( width: 0; height: 0; content: ''; z-index: 2; border-top: 1.5em solid currentColor; border-left: 1em solid transparent; border-right: 1em solid transparent; position: absolute; left: 50%; bottom: 100%; )