Aligning Page to a Specific Element Without Changing the DOM or Utilizing References

My goal is to easily scroll to a specific element using #:

<a href="#element">Element</a>

<div name="element" />

While this method works effectively, it always takes me to the top of the element. I would prefer to have the element centered on the screen for the user.

I am a bit hesitant to rely on Javascript's scrollTo or other external libraries, as I will need this feature frequently. Since I am using React, I want to avoid overusing refs and slowing down my application. Ideally, I would like to achieve this using just HTML, but I'm open to using JavaScript as well. However, most of the solutions I have found involve modifying the DOM and/or using refs.

Answer №1

If you're looking for a more efficient method using just html/css, one approach is to utilize a hidden span within your div container. Here's an example:

html {
  scroll-behavior: smooth;
}
.space {
  width: 100%;
  height: 400px;
  background-color: blue;
}
#element {
  position: relative;
  top: -50vh;
  visibility: hidden;
}
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <meta http-equiv="X-UA-Compatible" content="ie=edge">
  <title>Document</title>
</head>
<body>
  <a href="#element">Element</a>
  <div class="space"></div>
  <p> some text </p>
  <div class="space"></div>
  <p> some text </p>
  <div class="space"></div>
  <div>
    <p>
      Your element
    </p>
    <span id="element">anchor </span>
  </div>
  <div class="space"></div>
</body>
</html>

Answer №2

From my knowledge, achieving the desired effect without some JavaScript is not possible. For the "centered" aspect, it will require some calculations.

<html>
  <head>
    <title>Document</title>
    <style>
      .placeholder {
        height: 1000px;
      }
    </style>
    <script>
      function scrollToDest(event) {
        var id = event.target.getAttribute("href");
        if (id.charAt(0) !== "#") return; // not a valid <a> element
        var dest = document.getElementById(id.substr(1));
        if (!dest) return; // no destination found;

        event.preventDefault();
        // calculate the top and bottom margin remained when dest is centered
        var margin = window.innerHeight - dest.clientHeight;
        // what if the dest's height is larger than viewport?
        if (margin < 0) margin = 0;
        window.scroll({ left: 0, top: dest.offsetTop - margin / 2, behavior: "smooth" });
      }
    </script>
  </head>
  <body>
    <div class="placeholder">
      <a href="#dest" onclick="scrollToDest(event)">Let's go!</a>
    </div>
    <div id="dest">ARRIVAL</div>
    <div class="placeholder"></div>
  </body>
</html>

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

Determine if a cookie is set in Vue.js without requiring a page refresh

My current goal with VUE is to make the login url disappear from the navigation bar as soon as the user logs in. After successfully logging in, the token cookie is set in the browser. However, the issue arises when the login url remains visible in the nav ...

Resetting an array of refs in a React Native component

A React Native application is built with the following component structure: export default function MyApp({ route, navigation }) { const [pageId, setPageId] = useState(1); const childRef = useRef(new Array()); useEffect(() => { // Need ...

How to eliminate rows with images in Exceljs

I created a worksheet with an image in each row. However, when I filter or remove a row, the image for that row stays visible. I tested this on versions v4.4.0 and v4.3.0 I attempted various methods of adding images, but none of them seemed to work. Initi ...

Aligning images within a horizontal layout

I am facing an issue with my horizontal navigation list, where I am trying to place images/icons above the text in each list item. Despite all the images being the same size, I am struggling to center them properly within the list items. Here is the HTML ...

I am unable to utilize NavLink unless it is within the confines of the <Router> component

I am currently developing a React application using react-router-dom. To enhance the user experience with smooth transitions, I integrated framer-motion for page animations. However, I encountered an issue where my navbar was being animated and recreated e ...

Navigating and Displaying Views with React and Express

As a beginner in web development, I successfully completed a project using Node, Express, and EJS (for the frontend). Now, I am eager to tackle another project with React as my frontend. Despite watching numerous React + Express tutorials on YouTube, I not ...

What is the method for adding the square root symbol to a button's value?

I am attempting to display the square root symbol inside a button, but I am having trouble making it work. Below is my button code: <input type="button" id="sqrt" value="sqrt" onclick="insert function here"> For the value, I want the square root sy ...

"Utilizing the Redux store for state management within Axios interceptors in

I have encountered an issue while trying to access the redux store in axios's interceptor for configuring jwt token. I attempted to import the store into the API.js file, but it resulted in some errors being logged immediately.https://i.sstatic.net/5L ...

The journey of a JavaScript file within an iframe devoid of any src attribute

Consider this scenario: In a folder labeled /jscript, there are two files named my_js_file1.js and my_js_file2.js. I also have an /index.html page structured like this: <html> <head> <script type='text/javascript' sr ...

Using Promise to manipulate objects and arrays returned from functions

https://i.stack.imgur.com/jvFzC.png router.get('/', function (req, res, next) { var size = req.params.size ? parseInt(req.params.size) : 20; var page = req.params.page ? req.params.page>0 ? (size&(parseInt(req.params.page)-1)) : ...

Show the output of a MySQL query on a modal, alert, or popup box within a webpage initiated by a search box, with the option to close the

Having worked in IT for 16 years, I am new to coding and seeking help on displaying search results from an input HTML box. I want the data from a MySQL database to be displayed in a modal, alert, or popup box with a closing "X" button. This database only c ...

Adjust the HTML 5 range slider to update according to the selected value

Is it possible to create a custom marker on an HTML5 range input element? I'm looking for a way to change the design of the circle marker as it moves along the scale from 1 to 10. Specifically, I want to change the color of the marker based on its po ...

Angular application across multiple subdomains

Currently creating an angular application that allows users to generate and share digital books with a subdomain link like mycoolbook.theappsite.com. However, I've set up the routes so that editing books are at the URL "mycoolbook.theappsite.com/sett ...

Set font size for HTML elements based on different screen sizes in MaterialUI

I am venturing into the world of materialUI for the first time, moving away from CSS/SASS. I am facing an issue with the CSS reset process. Normally, I would set the font-size property on the HTML element to 62.5% so that everything aligns perfectly at 10p ...

The TD border is slicing through the div and is placed on the table in IE standards, causing it

Below is the HTML code where the div is being cut by the table border when the page is in standards mode. Interestingly, if I remove the <!DOCTYPE html>, then it works fine as expected. The issue of the outside div not behaving properly on the table ...

The transparency of the navigation menu is perplexing to me. I am unclear as to the reasoning behind it. I desire a

I am currently using a pre-made WordPress theme. Recently, I incorporated particles.js as the background for my website. The issue I am facing now is that my navigation menu is blending into the same color as the background. I have tried defining a separat ...

Activate a side navigation bar in AdminLTE-3

I am using AdminLTE3 as my admin panel in Laravel, but I am facing an issue with the nav-item links not activating when clicked. Even though I have all the required assets for AdminLTE3 and used the starter.html file, the navigation items are not working p ...

What is the best way to ensure that this image is responsive and not overly tiny when viewed on Internet Explorer

Check out my website: Here's a snapshot of the problem: I've been struggling to make my image responsive and prevent it from shrinking on IE 8. The webpage functions well on most modern browsers except for IE 8. I want it to display properly ac ...

Creating a dynamically generated JavaScript array using the JSON format

I am in need of creating an array of JSON data. Here is an example: [ { "DataCategoryGroupId": "22222222-2222-2222-2222-222222222222", "AnswerOptionIds": [ "76e32546-0e26-4037-b253-823b21f6eefb", "10d02a3e-9f9f- ...

Switching from Bootstrap's traditional "loading" style progress bar to a more minimal dot style progress bar

Currently, I am implementing a survey progress bar using Bootstrap's "loading" style. Here is the code for the progress bar: <div class="progress" style="height: 20px;"> <div class="progress-bar" role="pro ...