javascripthtmlcsscss-shapestext-rotation

How do I write over a triangle-shaped div using CSS?


I'm currently trying to write words over a triangle-shaped div that I created using CSS.

Here:

.triangle-topright {
  width: 0;
  height: 0;
  border-top: 100px solid gray;
  border-left: 100px solid transparent;
}
<div class="triangle-topright">view</div>

As you can see, view is misplaced as I want it to be inside the shape. I also want it to rotate so It's nice for the eye. I know that text rotation goes something like this (example):

-moz-transform: rotate(-90deg);

Can I achieve the goal using CSS or do I need to add some JS?

Thanks a lot!


Solution

  • Use pseudo elements

    DEMO - 1

    .triangle-topright {
      width: 100px;
      height: 100px;
      transform: rotateZ(45deg);
      margin: 20px;
      position: relative;
      z-index: 1;
      text-align: center;
      line-height: 64px;
    }
    
    .triangle-topright:before {
      content: '';
      z-index: -1;
      position: absolute;
      top:0;
      left: 0;
      width: 0;
      height: 0;
      transform: rotateZ(-45deg);
      border-right: 100px solid gray;
      border-bottom: 100px solid transparent;
    }
    <div class="triangle-topright">view</div>

    DEMO - 2

    .triangle-topright {
      width: 100px;
      height: 100px;
      margin: 20px;
      position: relative;
      z-index: 1;
      text-align: center
    }
    
    .triangle-topright:before {
      content: '';
      z-index: -1;
      position: absolute;
      top:0;
      left: 0;
      width: 0;
      height: 0;
      border-top: 100px solid gray;
      border-left: 100px solid transparent;
    }
    <div class="triangle-topright">view</div>

    DEMO - 3

    .triangle-topright {
      width: 100px;
      height: 100px;
      transform: rotateZ(90deg);
      margin: 20px;
      position: relative;
      z-index: 1;
      text-align: center
    }
    
    .triangle-topright:before {
      content: '';
      z-index: -1;
      position: absolute;
      top:0;
      left: 0;
      width: 0;
      height: 0;
      border-top: 100px solid gray;
      border-left: 100px solid transparent;
    }
    <div class="triangle-topright">view</div>

    DEMO - 4

    .triangle-topright {
      width: 100px;
      height: 100px;
      transform: rotateZ(90deg);
      margin: 20px;
      position: relative;
      z-index: 1;
      text-align: center
    }
    
    .triangle-topright:before {
      content: '';
      z-index: -1;
      position: absolute;
      top:0;
      left: 0;
      width: 0;
      height: 0;
      border-top: 100px solid gray;
      border-right: 100px solid transparent;
    }
    <div class="triangle-topright">view</div>