Deep out: How to use CSS Border to make triangles?
In front-end development, we often need to achieve graphics such as the little angle of the Tooltip, the arrows of the drop-down menu. Although... SVG is an option, but...
Pure CSS triangle
With its very simple code volume and zero request cost, it remains the developmentists ' preferred choice. This tool is manipulated.
border
The transparency of the properties, which generate these fine graphics for you in real time.
1. The working principles of the CSS triangle
Why set up?
border
Can you create a triangle? ♪ When an element ♪
width
and
height
When all 0, its four borders actually converge at the centre. If we make the three borders transparent (
transparent
) and set colour for only one of them, a triangle is born.
2. Addressing the alignment challenge: how can the triangle be put in the middle?
The generation code is only the first step, and how it is applied to the project is usually subject to positioning problems:
-
Absolute location:
Use
position: absolute;Mounts a triangle on a parent element (e.g., bubble box). -
Hypocrisy:
It's strongly recommended.
::beforeor::afterto create a triangle so that the HTML structure is kept simple. -
Offset correction:
If your triangle is down, it usually needs to be set.
left: 50%; transform: translateX(-50%);achieve horizontal centering.
3. Common application scenarios
master the triangle generator, you can easily achieve the following UI components:
- Bubbles dialogue box (Popovers): Adds a small triangle to the edge of the dialogue box, pointing to the button that triggers it.
- Collapse panel arrow: Switch the direction of the triangle (up or down) depending on the state of expansion/recycling.
- Multi-level menu indicator: Places a right-to-right triangle on the right side of the parent menu, prompting users to have a submenu.
Performance and advantages
CSS triangles have the following advantages compared to pictures (PNG/JPG):
- Response friendly: Just change the pixel value of the border-width, the triangle can be perfectly scaled, without ambiguity.
-
Colours are easy to control:
Directly through CSS.
border-colorto change the colour without redesigning the picture. - Zero delay: It is a direct drawing by the browser ' s rendering engine, which is not web downloadable and is very friendly to FCP (first content mapping) indicators.