css triangle using the border

You can easily generate a triangle on any side of your box grid, just need to do some minor changes in CSS.

HTML Code:

<div class="tooltip">
<p>Box title</p>
<span class="triangle"></span>
</div>

 

CSS to generate a triangle.

*, *::after, *::before {
box-sizing: inherit;
}

html {
box-sizing: border-box;
}

body {
padding: 2em;
}

.tooltip {
position: relative;
background-color: silver;
width: 200px;
height: 50px;
border-radius: 0.25em;
display: flex;
justify-content: center;
align-items: center;
}

.triangle {
display: block;
height: 0px;
width: 0px;
border: 10px solid transparent;
border-top-color: silver;
position: absolute;
bottom: -20px;
left: calc(50% – 10px);
}

 

Above code will generate a box with a triangle like

Here are some CSS changes to set a tringle to different positions.

To set triangle on top position:

.triangle {
border-bottom-color: silver;
top: -20px; 
}

 

Output:

To set triangle on right position:

.triangle {
 border-left-color: silver;
 right: -20px;
 //left: calc(50% - 10px);
}

 

Output:

To set triangle on left position:

.triangle {
 border-right-color: silver;
 left: -20px;
 //left: calc(50% - 10px);
}

 

Output:

 

 

Leave a Reply

Your email address will not be published. Required fields are marked *