Search code examples
htmlcsscss-shapes

Make an element non-rectangular in CSS to write text


I have a heading element which is supposed to have a trapezium like shape. The text inside the heading element has to follow the boundary of the trapezium instead of a rectangular box.

Is it possible to do so in CSS?

Here is a reference image:

enter image description here

As you can see, the text is rectangular in shape and does not respect the boundary of the black background.

Here is my CSS and HTML so far:

div.container {
  width: 1920px;
  height: 1080px;
  background: linear-gradient(120deg, black 50%, white 50%);
}
h1 {
  font-size: 3.5rem;
  padding: 2rem 1rem;
  color: white;
  text-align:  center;
  width: 940px;
}
<div class="container">
	<h1>This is any random piece of text.</h1>
</div>

I tried adding another div before h1 and apply the shape-outside property on it but no matter what value I give it. Nothing change.

Thanks.


Solution

  • You’re currently achieving the white shape by setting a background gradient. Instead, use shape-outside to actually create the shape and let the text wrap around it. Like this:

    .container {
      width: 400px;
      height: 200px;
      background-color: black;
      color: white;
    }
    
    .shape {
      width: 100%;
      height: 200px;
      background-color: white;
      -webkit-shape-outside: polygon(100% 0, 100% 100%, 0 100%);
      shape-outside: polygon(100% 0, 100% 100%, 0 100%);
      float: right;
      -webkit-clip-path: polygon(100% 0, 100% 100%, 0 100%);
      clip-path: polygon(100% 0, 100% 100%, 0 100%);
    }
    
    p {
      text-align: left;
    }
    <div class="container">
      <div class="shape"></div>
      <p>
        Lorem ipsum dolor sit amet, consectetur adipiscing elit. Morbi eu erat pharetra orci rhoncus dignissim. Nullam imperdiet justo felis, id venenatis velit pretium in. Donec commodo odio nisl, ut facilisis dui vulputate at. Nullam feugiat semper urna non efficitur. 
      </p>
    </div>

    Hope that helps!