0

TLDR:

I want a URL https://www.example.com/horses.html#two to dynamically vertically centre the hash identified part on the screen, on any device.

The Issue:

When using a URL link the hash location (in the above example #two) is placed at the top of the browser window. I am trying to find a way that the hashed link is vertically centred in the browser window on any device.

My usual work around for this sort of centering is to place the hash in the preceeding page area so as to create a natural margin at the top of the screen. However, on small screens and mobile devices this causes the intended target to sometimes be off screen and too low down.

Qualifier:

Please make the assumption in all situations that the HTML vertical size will always exceed the screen's vertical dimensions.

Example Code:

#one  {
  background-color:#ccf;
}
#two {
   background-color:#cfc;
}
p {
    padding:2rem 1rem;
    line-height:1.75rem;
}
<html>
<body>
  <div id='one'>
  <p>This is the first div area</p>
  <p>The UEFA Euro 2008 Final was the last match of Euro 2008, UEFA's competition for national football teams. The match was played at Ernst-Happel-Stadion (pictured), Vienna, Austria, on 29 June 2008, and was contested by Germany and Spain. The sixteen-team tournament had a group stage, from which eight teams qualified for the knockout phase. Germany lost to Croatia and beat Poland and Austria in Group B, and defeated Portugal and Turkey in the knockouts. Spain beat Russia, Sweden and Greece in Group D, and defeated Italy and Russia again in the elimination games. The final took place in front of 51,428 supporters and was refereed by Roberto Rosetti from Italy. Spain took the lead in the 33rd minute through Fernando Torres. There were no more goals and Spain won 1–0 to secure their second European title. Torres was named the man of the match. Spain went on to win the 2010 FIFA World Cup in South Africa, and retained their European</p>
<p><More filler text: </p>
<p>A rocket (from Italian: rocchetto, lit. 'bobbin/spool')[nb 1][1] is a spacecraft, aircraft, vehicle or projectile that obtains thrust from a rocket engine. Rocket engine exhaust is formed entirely from propellant carried within the rocket.[2] Rocket engines work by action and reaction and push rockets forward simply by expelling their exhaust in the opposite direction at high speed, and can therefore work in the vacuum of space.

In fact, rockets work more efficiently in the vacuum of space than in an atmosphere. Multistage rockets are capable of attaining escape velocity from Earth and therefore can achieve unlimited maximum altitude. Compared with airbreathing engines, rockets are lightweight and powerful and capable of generating large accelerations. To control their flight, rockets rely on momentum, airfoils, auxiliary reaction engines, gimballed thrust, momentum wheels, deflection of the exhaust stream, propellant flow, spin, or gravity.</p>

<p>Rockets for military and recreational uses date back to at least 13th-century China.[3] Significant scientific, interplanetary and industrial use did not occur until the 20th century, when rocketry was the enabling technology for the Space Age, including setting foot on the Earth's moon. Rockets are now used for fireworks, weaponry, ejection seats, launch vehicles for artificial satellites, human spaceflight, and space exploration.</p>

<p>Chemical rockets are the most common type of high power rocket, typically creating a high speed exhaust by the combustion of fuel with an oxidizer. The stored propellant can be a simple pressurized gas or a single liquid fuel that disassociates in the presence of a catalyst (monopropellant), two liquids that spontaneously react on contact (hypergolic propellants), two liquids that must be ignited to react (like kerosene (RP1) and liquid oxygen, used in most liquid-propellant rockets), a solid combination of fuel with oxidizer (solid fuel), or solid fuel with liquid or gaseous oxidizer (hybrid propellant system). Chemical rockets store a large amount of energy in an easily released form, and can be very dangerous. However, careful design, testing, construction and use minimizes risks. </p>
  </div>
  <div id='two'><p>This is the second div area. This will appear at the top of the screen from the link in the third div area, below.</p>
  
<p>In Autumn 1995, the Icelandic Minister of Education, Science and Culture, Björn Bjarnason, suggested that one day a year should be proposed to celebrate the Icelandic language, which has been well-preserved in its original form over the centuries, unlike most other languages; and the efforts to preserve this unique symbol of the country.</p></div>
  <div id='three'><p><strong>This is the third div area.<BR><BR>  <a href='#two'>This link</a> should centre the second div area in the screen rather than at the top of the page.</strong></p>
  <p>filler: Icelandic Language Day (Icelandic: dagur íslenskrar tungu, English: "day of the Icelandic tongue") is a festival celebrated on 16 November each year in Iceland to celebrate the Icelandic language. This date was chosen to coincide with the birthday of the Icelandic poet Jónas Hallgrímsson.</p>


<p>As such, on 16 November, the Minister of Education, Science and Culture awards the Jónas Hallgrímsson Award to someone who has “in a unique way contributed to the Icelandic language”.[1] The Minister may also visit a local area of Iceland's schools and cultural institutions, for example in 2004 Þorgerður Katrín Gunnarsdóttir visited Ísafjörður and in 2005 she visited Reykjanesbær. </p>

<p>Filler text for horses and full screen example</p>
<p>The horse (Equus ferus caballus)[2][3] is a domesticated one-toed hoofed mammal. It belongs to the taxonomic family Equidae and is one of two extant subspecies of Equus ferus. The horse has evolved over the past 45 to 55 million years from a small multi-toed creature, Eohippus, into the large, single-toed animal of today. Humans began domesticating horses around 4000 BC, and their domestication is believed to have been widespread by 3000 BC. Horses in the subspecies caballus are domesticated, although some domesticated populations live in the wild as feral horses. These feral populations are not true wild horses, as this term is used to describe horses that have never been domesticated. There is an extensive, specialized vocabulary used to describe equine-related concepts, covering everything from anatomy to life stages, size, colors, markings, breeds, locomotion, and behavior.</p>

<p>Horses are adapted to run, allowing them to quickly escape predators, possessing an excellent sense of balance and a strong fight-or-flight response. Related to this need to flee from predators in the wild is an unusual trait: horses are able to sleep both standing up and lying down, with younger horses tending to sleep significantly more than adults.[4] Female horses, called mares, carry their young for approximately 11 months, and a young horse, called a foal, can stand and run shortly following birth. Most domesticated horses begin training under a saddle or in a harness between the ages of two and four. They reach full adult development by age five, and have an average lifespan of between 25 and 30 years.</p>

<p>Horse breeds are loosely divided into three categories based on general temperament: spirited "hot bloods" with speed and endurance; "cold bloods", such as draft horses and some ponies, suitable for slow, heavy work; and "warmbloods", developed from crosses between hot bloods and cold bloods, often focusing on creating breeds for specific riding purposes, particularly in Europe. There are more than 300 breeds of horse in the world today, developed for many different uses.</p>

<p>Horses and humans interact in a wide variety of sport competitions and non-competitive recreational pursuits, as well as in working activities such as police work, agriculture, entertainment, and therapy. Horses were historically used in warfare, from which a wide variety of riding and driving techniques developed, using many different styles of equipment and methods of control. Many products are derived from horses, including meat, milk, hide, hair, bone, and pharmaceuticals extracted from the urine of pregnant mares. Humans provide domesticated horses with food, water, and shelter, as well as attention from specialists such as veterinarians and farriers. </p>

</div>
</body>
</html>

The example code should give you an idea but doesn't really display it well due to be constrained in an iframe

Old Similar Questions:

This question - Javascript/jquery window.location.hash move to center of screen - asks a very similar thing but has not been changed in over 7 years and I was hoping there was developments in this respect....

Likewise, this question - How to vertically center a div on the available screen height? - kind of asks the right concept but the Q&A are forcing the element (using CSS) to always be centred as a style choice. This is not what I am looking for.

Can It Be Done?

A javascript offset that when an internal or external link loads with a location hash that the hash anchor (#two) is vertically (and if needbe horizontally) centred in the screen without manually positioning elements and offsets.

I have found how to access the location hash via JS but how to centre it is tricky; all I find are Q&A about how to take the div/element out of the flow of the document and centre them as an exception rather than in their natural flow position.

I have found a conceptual solution but it uses prototype and is from back in 2012!

Other Reading I've done:

Martin
  • 20,858
  • 7
  • 60
  • 113

0 Answers0