Tips for adding styles to the first and last elements of a printed page

I have created a dummy code example that generates multiple paragraph elements with some text in it. However, I need to add borders to the first and last elements to enhance the design. Here is the code snippet:

<!doctype html>
<html>
  <head>
    <style>
      p {font-size: 20px;}
    </style>
  </head>
  <body>
    <script type="text/javascript">
      window.onload = function () {
        var body = document.getElementsByTagName('body')[0],
            p = document.createElement('p'),
            el;

          p.style.height = '20px';
          p.innerText = 'Some Test';

        for (var i = 0, len=30; i<len; i++) {
          el = p.cloneNode(true);
          body.appendChild(el);
        }
      };
    </script>
  </body>
</html>

Unfortunately, the CSS solutions I've found so far don't work as intended. I need a solution that specifically targets the first and last elements, and works in Chrome. Any suggestions on how to achieve this?

EDIT: Some of the suggested CSS solutions include:

p:nth-child(1){
 border-top : solid 1px gray;
}
p:last-child{
   border-top : solid 1px gray;
}

or

p:first-child {border-top : solid 1px gray;}
p:last-child {border-bottom : solid 1px gray;}

However, these solutions apply the styles to all paragraph elements, not just the first and last ones. I need a solution that targets only the first and last elements, and works specifically in Chrome.

Answer №1

If you're looking for a more advanced solution, one approach could involve determining the viewable page height using JavaScript or jQuery to calculate how many items can fit on a single page. You can then apply specific styles to the desired elements using nth-child(x) selectors. While not the most straightforward method, this could be effective if you have specific requirements such as browser compatibility or operating system constraints.

EDIT:

Here is a potential solution: http://jsfiddle.net/VKDVd/

HTML: Simply use placeholder divs... Make sure to set your doctype correctly for $(window).height() to function properly!

JavaScript/jQuery:

$(document).ready(function () {

    // If including images, consider using $(window).load(function() {[...]} to ensure they are fully loaded before calculating heights

    var pageHeight = $(window).height(); // JS-only and IE-compatible approach (see my answer)
    var sumElementHeights = 0;
    var count = -3; // Offset to ensure border is within viewport

    for (var i = 0; i < $('div').length && sumElementHeights < pageHeight; i++, count++) {
        sumElementHeights += $('div').eq(count).height(); // Total div heights
    }

    $('div').eq(0).css('border-top', '10px solid black');
    $('div').eq(count).css('border-bottom', '10px solid black');
    // You can loop this for each page as needed...       
});

PS: Consider adding code to adjust div borders if viewport size changes, like resizing the browser window.

PPS: Experiment with the count values based on the border sizes applied to elements.

Answer №2

To create a header and footer that appear on every page, you can use two containers positioned at the top and bottom of the page using position:fixed. This method is supported in Firefox, Opera, and Internet Explorer, but not in webkit browsers.

Check out the demo here


Based on some testing, the optimal CSS values for your containers are as follows:

#top {
  height: 2px;
  position: fixed;
  width: 100%;
  top: 0;
  left: 0;
  border-bottom: 1px solid #000;
}
#bottom {
  height: 2px;
  position: fixed;
  width: 100%;
  left: 0;
  bottom: 1px;
  border-top: 1px solid #000;
}
p {
  padding-top: 20px;
}

Don't forget to structure your HTML like this:

<div id="top"></div>
<div id="bottom"></div>
<p>abc</p>
<p>abc</p>
.....

Answer №3

If you couldn't care less about supporting outdated browsers, this solution is for you...

@media print
  {
      p:nth-child(1){
          border-top : solid 1px gray;
      }
      p:last-child{
          border-bottom : solid 1px gray;
      }
  }

However, if you need compatibility with older browsers (especially IE), you'll need to implement a JavaScript workaround.

Answer №4

Experiment with first-child and last-child.

Take this example,

p {font-size: 20px;}
p:first-child {...} /* Insert your preferred style here */
p:last-child {...} /* Insert your preferred style here */

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

How to Trigger a Callback Function in Angular Template?

Within my directive for tables, I have the ability to output values based on specific properties. For example: <tr ng-repeat="item in table.data"> <td ng-repeat="column in table.columns"> <i ng-if="column.type === 'icon&apo ...

Troubleshooting Socket.IO Communication: Client's emits not reaching server

I have implemented a real-time notification service in a web app using Express and Socket.IO. The client can successfully connect to the server and receive emits from it. However, I am facing an issue where the server is not receiving emits from the client ...

Is there a way for me to gain entry to this array in vuejs?

Can anyone help me with accessing the objects in this array? I am using laravel, inertiajs, and vuejs. I am passing a variable from a laravel controller to a vuejs component with inertia.js. https://i.stack.imgur.com/p7yjL.png https://i.stack.imgur.com/y ...

Utilizing the scrollTop method to display the number of pixels scrolled on

My goal is to show the number of pixels a user has scrolled on my website using the scrollTop method in jQuery. I want this number of pixels to be displayed within a 'pixels' class. Therefore, I plan to have <p><span class="pixels"> ...

Modify the background color of the body when hovering over items in the unordered list using CSS

How can I modify the background color of the body when I hover over ul li using CSS? ...

Angular login/signup modal/dialog component for seamless user authentication

Currently, I am working on adding a login/signin dialog to my app similar to the one used by Medium. After doing extensive research online, I have decided to use the $modal from angular ui-bootstrap for this. Can anyone please recommend a tutorial that wil ...

Utilize Lodash to iterate through functions in a loop and retrieve the first matching result

I am looking to iterate through an array of objects and call a method on them. If the result of that method meets certain conditions, I want to immediately return that result. The current implementation is as follows: public getFirstMatch(value: string, a ...

Exploring values within an array of objects using Node.js

I have some data presented in the following format [ [ '@test','1.2.6' ], [ '@test2','4.0.1' ], [ '@test3','2.2.0-unstable' ], ... ] My goal is to extract all values that include -unstable, ...

Methods for scaling the size of CSS background images

Can anyone assist me with scaling background image size properly? code: http://codepen.io/AnilSimon123/pen/JRBRZa Below is the code snippet: .bgimage{ background:url('http://www.thedesignlove.com/wp-content/uploads/2012/08/free-blue-abstract-vec ...

Tips for Customizing the Width of Your Material UI Alert Bar

At the moment, I have refrained from using any additional styling or .css files on my webpage. The width of the Alert element currently spans across the entire page. Despite my attempts to specify the width in the code snippet below, no noticeable change ...

Make sure to execute a function prior to the ajax beforeSend

Before I upload a file using 'fileuploader', I attempted to check the file first in my beforeSend function: beforeSend: function(item, listEl, parentEl, newInputEl, inputEl) { var file = item.file; let readfile = functio ...

Exploring High-Density Mobile Devices with Bootstrap 3 Landscape Mode

After completing my first Bootstrap site using version 3, I noticed a display issue when viewing it on an iPhone 5 or LG G2 in landscape mode due to the pixel density. This was not a problem with the Responsive Grid system I previously used. Although I sp ...

What are the appropriate situations to utilize Q.defer versus using Promise.resolve/reject?

I've been working with nodejs and I'm curious about when to use Q defer over Promise.resolve/reject? There are numerous examples of both methods, such as: // using Q defer function oneWay(myVal) { var deferred = Q.defer(); if (myVal < 0) ...

How does the Angular2-all.umd.js compare to the angular2.js file?

Currently, Angular 2 is in its 13th beta phase. I came across https://code.angularjs.org/2.0.0-beta.13/ and noticed that there are two different versions of Angular2 available: angular2-all.umd.js angular2.js What distinguishes these two versions from ...

What is the best way to conceal two Bootstrap divs that should not both be visible at the same time?

I am working with two different types of charts: an Emotion chart and a Polarity chart. To control the visibility of these charts, I have implemented two buttons, one for each chart. The functionality is such that when the first button is clicked, only the ...

Tips for creating an expression within ng-if

I am struggling with placing an expression inside ng-if that needs to be assessed in order for my content to be shown based on its outcome. This is what I currently have: <a ng-if="abc.status===failure" href="http://localhost:3000/abc/abc">image< ...

Reading multiple files in NodeJS can be done in a blocking manner, and then the

When retrieving a route, my aim is to gather all the necessary json files from a directory. The task at hand involves consolidating these json files into a single json object, where the key corresponds to the file name and the value represents the content ...

Utilize Google Chrome Developer Tools to interact with the "Follow" buttons on the webpage by clicking on them

https://i.stack.imgur.com/W32te.png Here is the script I am currently using: document.querySelectorAll('.components-button components-button-size-mini components-button-type-orange desktop components-button-inline').forEach(btn => btn.click() ...

AngularJS Reload Scenario: A new way to refresh and enhance

My current project involves the development of a mobile app where I am retrieving data from a REST GET call. Everything is running smoothly. However, I would greatly appreciate expert advice on how to seamlessly re-render this data if the user decides to ...

Deactivate the button once it's been used | Discord.js version 14

In my index.js, I created a function to respond when a button is pressed and then disable it. client.on("interactionCreate", async (interaction) => { if (interaction.isButton()) { if (interaction.customId === "yes") { co ...