I need for the code section shown in pre to point to a particular line number. If there are 100 lines in pre I want what is shown to be line 51 for right in the center of the 150px box.
Asked
Active
Viewed 1.0k times
3 Answers
13
Try this (for 10 lines):
<pre style="width: 300px; height: 10pc; overflow-y: scroll;">
1
2
3
4
5
6
7
8
9
10
11
12
</pre>
Note "pc" instead "px"
-
27 years later ... an explanation of how this is supposed to work would be nice. BTW: `pc` is pica: One pica. `1pc` = `12pt` = 1/6th of `1in`. See [CSS values and units](https://developer.mozilla.org/en-US/docs/Learn/CSS/Introduction_to_CSS/Values_and_units) and [`
`](https://developer.mozilla.org/en-US/docs/Web/CSS/length) on MDN. But like pixels, this is also an absolute length unit (`1px` = 1/96th of `1in`), and as such there are many situations where this probably does not work. – handle Oct 23 '18 at 09:23
0
You can do this using scrollTop in jQuery:
$("#code").scrollTop(topPosition);
where scrollPosition
is "the number of pixels that are hidden from view above the scrollable area".
The difficulty is working out what this value should be. If you know the height of each line (which you can set using font-size
in CSS, you could use:
topPosition = lineHeight * (lineNumber - 1);
But then you want the specified line to be in the middle of the container, so perhaps:
topPosition = lineHeight * (lineNumber - 1) - 70;
if (topPosition < 0) topPosition = 0;
I would play around with this and see if you can make it work. :)

James
- 7,343
- 9
- 46
- 82
0
To achieve that, you need a fixed line height for your pre
element. For 150px height I suggest 15px for line-height
and 11px for font-size
. This will ensure 10 lines in your scrollable area.
The rest is some math and using scrollTop
property.
example:
function goToLine(centeredLine){
var pre = document.getElementById('scrollablePre');
pre.scrollTop = (centeredLine - 5) * 15;
};

dev-null-dweller
- 29,274
- 3
- 65
- 85