What is the best way to align my clip-path's text with the center of the viewport and ensure that all of the clip-path's text is visible?

Check out my React component demo: https://codesandbox.io/s/epic-brown-osiq1. I am currently utilizing the values of viewBox, getBBox, and getBoundingClientRect() to perform calculations for positioning elements. At the moment, I have hardcoded some values based on the output from console logs generated by getBoundingClientRect(). You can observe this implementation on the root element of the SVG and the text element within the clip-path. The alignment of the text is close but not perfectly centered. Feedback is welcome.

Note: Some comments in the sandbox provide insights into previous attempts. What my code does: It displays a clipped text with an animated panel moving along the clip-path to add dynamism to the composition. Additionally, there's a shadow effect behind the text for depth.

  • Expectation: Display the clipped text at the vertical and horizontal centers of the viewport.
  • Problem: The clip-path hides part of the text, and attempts to center the element relative to the viewport have been unsuccessful.
  • What I have tried: Various adjustments to the width and x positions of elements such as text, clip-path, symbol, etc., using CSS classes directly on SVG elements, implementing position absolute on a container, and more. Results have been approximate at best.

I'm seeking clarification on why my code behaves the way it does.

Below is a sample resulting code (what the React component generates):

...CSS Code here...
...HTML/SVG Code here...

Any help or suggestions are appreciated.

Answer №1

When it comes to text alignment in SVG, the process works differently compared to HTML and CSS. Unlike the box model in CSS where dimensions are set and alignment is straightforward using properties like text-align: center, working with text alignment in SVG involves defining starting coordinates from which the text line expands.

The <svg:text> element uses starting coordinates to determine the expansion direction of the text line. The text-anchor attribute plays a crucial role in controlling this expansion. For instance, setting the value to center ensures that the text expands evenly on both sides, with the initial anchor point aligned at the middle of the bounding box width for horizontal writing systems. Check out an informative answer demonstrating the use of text-anchor to center text in SVG here: . Moreover, unlike HTML, SVG does not support CSS position properties such as left/top; instead, it relies on x/y coordinates without margins or other box model features.

To achieve centered text in your code, adding the attribute text-anchor="middle" and adjusting the x coordinate position would result in properly aligned text. It's recommended to use bare <text> elements rather than <tspan> elements when aligning text in SVG. Shifting tspan with dx/dy attributes can lead to unbalanced centering due to spaces inherited from parent <text>. Additionally, using dominant-baseline="central" (or simply middle for horizontal writing) facilitates easier positioning by moving the anchor point to the "center line" rather than the base line. Utilizing the dy attribute to adjust the text lines' vertical spacing can help achieve the desired centering effect:

<svg viewBox="0 0 800 200" text-anchor="middle" dominant-baseline="central" font-size="100">
 <!-- Outline and diagonals with center point for illustration: -->
 <path d="M0,0h800v200h-800zl800,200m0 -200L0,200" fill="#FC9" stroke-width="1" stroke="rgba(0,0,0,0.3)"></path>
 <circle cx="50%" cy="50%" r="10" fill="red"></circle>
 <!-- Centered text: -->
 <text x="50%" y="50%" fill="rgba(0,0,0,0.3)">So</text>
 <!-- Shifted up and down: -->
 <text x="50%" y="50%" dy="-0.5em">So</text>
 <text x="50%" y="50%" dy="+0.5em">Food</text>
</svg>


(On a side note: achieving clipping effects solely through CSS can be done using background-clip: text. Here's an example showcasing a rough variation of your design in Chrome browser, featuring animated text backgrounds without shadows. Unfortunately, adding shadows may require additional elements or attributes. This styling should work across browsers supporting background-clip.)

div {
display: flex;
flex-direction: column;
align-items: center;
font-size: 30vh;
line-height: 30vh;
font-weight: bold;
font-family: Impact;
}
span {
color: #fff;
background-color: #000;
width: 100%;
text-align: center;
}
@supports (-webkit-text-fill-color: transparent) and (-webkit-background-clip: text) {
span {
-webkit-text-fill-color: transparent;
-webkit-background-clip: text;
animation: 2s wohoo infinite alternate cubic-bezier(1,0,1,1);
background-position: 0 0;
background-size: 100% 100%;
background-color: transparent;
background-image: linear-gradient(
to right,
#f2385a 0,
#f2385a 20%,
#f5a503 0,
#f5a503 40%,
#e9f1df 0,
#e9f1df 60%,
#56d9cd 0,
#56d9cd 80%,
#3aa1bf 0,
#3aa1bf 100%
);
background-repeat: no-repeat;
transform-origin: center center;
}
}

@keyframes wohoo {
from {
background-size: 0 100%;
background-position: -5vh 0;
transform: scale(0.7);
}
50% {
transform: scale(0.7);
}
90% {
transform: scale(0.9);
}
to {
background-size: 500% 100%;
background-position: 0vh 0;
transform: scale(0.9) 
}
}

html,body{margin:0;overflow:hidden;}
body {
background-color: #1d1f20;
color: snow;
display: flex;
flex-direction: row;
justify-content: center;
width: 100%;
}
<div>
<span>Baz</span>
<span>Gazonk</span>
<span>Qux</span>
</div>

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Verify the data types of components received as props in a Typescript React application

I have a question regarding type checking in React components passed as props: What is the method for ensuring that only allowed components are passed as props? Allow me to demonstrate. We have the component we wish to pass around: type CustomProps = { ...

What steps can be taken to launch a website in Chrome's headless mode while navigating around any blockers of the mode itself

Below is the XPATH I am using to extract price information from various websites, except for Myntra. This XPATH works perfectly on my local Windows system with Selenium, Python3 version, and Chrome driver. Driver path: driver = webdriver.Chrome("/usr ...

CSS and the best practices for button styling in a navigation bar

My friend and I are facing a CSS issue while working on a webpage together. We both have limited experience with HTML and CSS. Here's the code snippet in question: .nav li { margin: auto; display: inline-block; color: white; padding: 10px; font ...

The elements at the bottom of the Google homepage do not stay in place when hovering

I'm facing an issue and seeking guidance on how to make the footer and 'Google in different languages' fixed when hovering over the buttons. I'm attempting to create this on my own without referencing the Google homepage code in Chrome ...

Delivering static HTML routes in a React App using Typescript

I am working on a React app with functional components, and everything is working perfectly with its own CSS. Now, I have a separate static HTML file (FAQ) with its own CSS and design that I want to incorporate as a new route at /FAQ. I don't want th ...

Implementing customized line breaks in PHP using custom fields

My knowledge of PHP is quite limited, so I prefer to seek advice from experts before attempting anything I find online. I recently installed a customized billing field plugin in order to collect additional billing information during the checkout process. ...

What is the process for initiating cross-component communication?

i am working with two different components that are each located in their own JSX files 1. on Component1.jsx : var Comp1 = React.createClass({ componentDidMount: function() { this.comp1Fn(); }, comp1Fn: funct ...

ng-class will not activate a custom directive

I have developed a custom AngularJS directive that should work on elements with the specified class name .collapse. However, when I apply this class using Angular's ng-class directive, the custom collapse directive does not get activated. Here is a ...

Adding client-side scripts to a web page in a Node.js environment

Currently, I am embarking on a project involving ts, node, and express. My primary query is whether there exists a method to incorporate typescript files into HTML/ejs that can be executed on the client side (allowing access to document e.t.c., similar to ...

Tell me the permissions that a user possesses in discord.js

I need help creating a command using Discord.js that can display a user's permissions. For instance, the command could be $permissions @user and it should output something like: "User permissions within this guild: " I'm unsure if ...

Guide on programmatically redirecting a user to a different route

I am currently working on a VueJS 3 application using Quasar, and I am facing difficulties with programmatically utilizing the Router. The issue can be summarized as follows: 1. The Challenge When attempting to navigate the User to a different route, onl ...

Determine the total number of elements within the Map tag using JSOUP

Hello, I am currently working on developing a web crawler using Java. One of the functionalities I need is to count the total number of sections present on the current page. These sections are located within area tags contained in a Map tag. Despite using ...

Incorporate spacing between columns in Bootstrap 5 by adding gutters

I've been exploring ways to incorporate spacing between my columns in Bootstrap 5. I diligently followed the guidelines provided in the documentation, but I'm facing difficulties in adding gutters between my columns. Currently, I am utilizing g- ...

Position CSS elements at the bottom of the webpage

I'm having trouble with my footer always being covered by dynamic content on my page. How can I adjust the CSS to make sure the footer stays at the bottom and adjusts to the size of the content? Here's the current CSS code for the footer: div ...

How can I resolve a MySQL query error in Node.js that is throwing an undefined error?

There seems to be an issue with the second request returning undefined instead of showing the results. The expected behavior is that if the first request returns less than two lines, the second request should be executed. What could be causing this error ...

AngularJS $scope variable is not defined during page load

Experiencing difficulties retrieving service data to include in the variable's scope. Below is my controller code: 'use strict'; var app = angular.module('ezcms2App.controllers', []); app.controller('NoticiaCtrl', [&apo ...

Is there a way for me to position my chat messages on the right side in the chat room?

I have a react chat application and I'm looking to customize the appearance of my messages. Currently, all entries with an orange vertical bar belong to me and are displayed on the left side of the chat room. I would like to move them to the right sid ...

React component properties fail to update

Hey there! I am currently working on developing a React Component that consists of a simple label which changes its content whenever a SignalR method is triggered. Below is an example of my React component: var PersonalityStatusApp = React.createClass({ ...

Can a complete form be encapsulated within a single AngularJS directive?

While I have come across several instances of individuals utilizing a blend of HTML and directives to craft an AngularJS form (as seen here), my goal is to develop a self-contained widget. This widget would encompass all the necessary HTML for the form w ...

Create a dynamically updating list using React's TypeScript rendering at regular intervals

My goal is to create a game where objects fall from the top of the screen, and when clicked, they disappear and increase the score. However, I am facing an issue where the items are not visible on the screen. I have implemented the use of setInterval to d ...