QThompson
QThompson

Reputation: 1708

How do I create trapezoid div with centered text?

I am trying to create a div shaped like a trapezoid and would like to place text in the center. I currently have a div with the top border shaped like a trapezoid. The problem with this is that the text is centered of the div but not in the center of the trapezoid. I could change the margin and manually place the the text in the center, but this would be too hacky and need the layout to be responsive to different screen sizes. I would like to make the body of the div a trapezoid and then it would be easy to center the text. I've looked all over the web for how to do this, but all the answers have the same approach with just making the top or bottom border the trapezoid.

import React from 'react'
import "../css/WelcomeScreen.css"

function WelcomeVisitor(){
    return (
        <div className="parentView">
            <div className="trapezoid">
            <h1 className="welcomeText"> Welcome </h1>
            </div>
        </div>
    )
}

export default WelcomeVisitor
.trapezoid {
    border-top: 125px solid white;
    border-left: 25px solid transparent;
    border-right: 25px solid transparent;
    width: 50%;
    display: flex;
    justify-content: center;
}

.welcomeText {
    color: white;
    display: flex;
}

.parentView {
    display: flex;
    border: 1px dotted red;
    flex-direction: column;
    align-items: center;
    height: 100vh;
    justify-content: space-between;
}

enter image description here

enter image description here

Upvotes: 2

Views: 1347

Answers (1)

thetont
thetont

Reputation: 810

The easiest way to get text in a trapezoid involves the clip-path property.

Something like this should work for your case:

clip-path: polygon(0% 0%, 100% 0%, 90% 100%, 10% 100%);

This property allow you to control the shape of your element's background.

here's the snippet with your code updated:

.parentView {
  display: flex;
  border: 1px dotted red;
  flex-direction: column;
  align-items: center;
  height: 100vh;
  justify-content: space-between;
  background: #000;
}

.trapezoid {
  background: #fff;
  width: 50%;
  display: flex;
  justify-content: center;
  clip-path: polygon(0% 0%, 100% 0%, 90% 100%, 10% 100%);
}

.welcomeText {
  color: red;
  display: flex;
}
<div class="parentView">
  <div class="trapezoid">
    <h1 class="welcomeText"> Welcome </h1>
  </div>
</div>

Upvotes: 1

Related Questions