What is the best way to align elements on the left side in the center of my page when they are not adjacent in the DOM structure?

Let's consider a scenario where my website is structured with a header, footer, and main column. The main column holds the article and its table of contents side by side, with the center alignment. The width of the main column isn't fixed due to the presence of the table of contents. I aim to align the header and footer content (enclosed within .main-column) so that it matches the left edge of the centered main column.

Putting the header and footer inside the <main> tag for centering is not an option because I want a border (like <hr>) to span across the entire viewport width.

An alternative solution would involve using JavaScript to set the margin-left of the header and footer. However, I prefer not to rely on JavaScript for layout purposes but rather reserve it for minor enhancements.

* {
  margin: 0;
  padding: 0;
}

header {
  border-bottom: 1px solid black;
}

footer {
  border-top: 1px solid black;
}

.main-column {
  /* this adjusts alignment */
  margin-left: 5rem;
}

main {
  display: flex;
  flex-direction: row;
  justify-content: center;
  align-items: flex-start;
}

article {
  max-width: 20rem;
}

nav {
  background: gray;
}

ul {
  margin-left: 1.5em;
}
<html>

<body>
  <header>
    <div class="main-column">
      <h1>Header here</h1>
    </div>
  </header>
  
  <main>
    <article>
      <h1>This is some article</h1>
      <p>Lorem ipsum dolor sit amet, consectetur adipiscing elit. Mauris mattis leo ut metus egestas porttitor eu ac risus. Fusce convallis posuere diam ut dapibus. Mauris at velit ex. Ut malesuada sollicitudin magna, ac imperdiet ipsum elementum in. In
        hac habitasse platea dictumst. Etiam egestas ligula sed erat vestibulum porta. Suspendisse potenti. Donec facilisis risus placerat tincidunt lacinia. Suspendisse potenti. Aliquam in pharetra lectus. Suspendisse sodales, erat iaculis auctor lacinia,
        augue dolor lobortis dui, quis fermentum neque nulla ac lacus. Morbi id nulla iaculis, laoreet dui eget, vehicula nulla. Donec eget purus sit amet nibh mollis tempor. Proin hendrerit nisi quis orci placerat ullamcorper. Integer congue mauris dui,
        vel tempor libero ultrices non. Aliquam in nisl magna.</p>
    </article>
    <nav>
      <h3>Table of contents</h3>
      <ul>
        <li>Some</li>
        <li>links</li>
        <li>here</li>
      </ul>
    </nav>
  </main>
  
  <footer>
    <div class="main-column">
      <h1>Footer here</h1>
    </div>
  </footer>
</body>

</html>

Answer №1

A potential solution I have discovered involves adjusting the DOM structure so that all content can be centered within a single div. By implementing negative margins, we can create borders that extend beyond this centralized container.

However, one drawback of this approach is the necessity of adding overflow-x: hidden to the entire page, which may not be ideal depending on other elements present.

* {
  margin: 0;
  padding: 0;
}

#container {
  display: grid;
  justify-content: center;
}

#wrapper {
  display: inline-block;
}

main {
  display: flex;
  flex-direction: row;
  align-items: flex-start;
}

article {
  max-width: 15rem;
}

nav {
  background: gray;
}

ul {
  margin-left: 1.5em;
}

header hr, footer hr {
  height: 0;
  border: none;
  border-bottom: 1px solid black;
  margin: 0 calc(50% - 50vw);
}

body {
  overflow-x: hidden;
}
<html>

<body>
<div id="container">
<div id="wrapper">
  <header>
    <h1>Header here</h1>
    <hr>
  </header>
  
  <main>
    <article>
      <h1>This is some article</h1>
      <p>Lorem ipsum dolor sit amet, consectetur adipiscing elit. Mauris mattis leo ut metus egestas porttitor eu ac risus. Fusce convallis posuere diam ut dapibus. Mauris at velit ex. Ut malesuada sollicitudin magna, ac imperdiet ipsum elementum in. In
        hac habitasse platea dictumst. Etiam egestas ligula sed erat vestibulum porta. Suspendisse potenti. Donec facilisis risus placerat tincidunt lacinia. Suspendisse potenti. Aliquam in pharetra lectus. Suspendisse sodales, erat iaculis auctor lacinia,
        augue dolor lobortis dui, quis fermentum neque nulla ac lacus. Morbi id nulla iaculis, laoreet dui eget, vehicula nulla. Donec eget purus sit amet nibh mollis tempor. Proin hendrerit nisi quis orci placerat ullamcorper. Integer congue mauris dui,
        vel tempor libero ultrices non. Aliquam in nisl magna.</p>
    </article>
    <nav>
      <h3>Table of contents</h3>
      <ul>
        <li>Some</li>
        <li>links</li>
        <li>here</li>
      </ul>
    </nav>
  </main>
  
  <footer>
    <hr>
    <h1>Footer here</h1>
  </footer>
</div>
</div>
</body>

</html>

Answer №2

It seems like you're looking for a solution where the width of the main content is dynamic, but there's a need to utilize some box model properties.

* {
  margin: 0;
  padding: 0;
}

#wrapper {
  display: flex;
  justify-content: center;
  overflow-x: hidden;
}

#container {
  border: rgba(255,0,0,.2) 2px dashed;
  display: inline-flex;
  flex-direction: column;
}

hr {
  margin: 0;
  border: 0;
  border-bottom: #000 1px solid;
  margin: 0 -100%;
}

main {
  display: flex;
  flex-direction: row;
  justify-content: center;
  align-items: flex-start;
}

article {
  max-width: 25rem;
}

nav {
  background: gray;
}

ul {
  margin-left: 1.5em;
}
<html>

<body>

<div id="wrapper">
  <div id="container">

    <header>
      <div class="main-column">
        <h1>Header here</h1>
      </div>
      <hr>
    </header>

    <main>
      <article>
        <h1>This is some article</h1>
        <p>Lorem ipsum dolor sit amet, consectetur adipiscing elit...</p>
        <p>Lorem ipsum dolor sit amet, consectetur adipiscing elit...</p>
        <p>Lorem ipsum dolor sit amet, consectetur adipiscing elit...</p>
      </article>
      <nav>
        <h3>Table of contents</h3>
        <ul>
          <li>Some</li>
          <li>links</li>
          <li>here</li>
        </ul>
      </nav>
    </main>

    <footer>
      <hr>
      <div class="main-column">
        <h1>Footer here</h1>
      </div>
    </footer>
    
  </div>
</div>

</body>

</html>

If you find DOM structuring challenging, consider using the following JavaScript approach instead for an easier solution:

// Wait for the DOM nodes to merely be present...
document.addEventListener('DOMContentLoaded', function (e) {
  const getEl = function(tag) { return document.getElementById(tag) },
        header = getEl('header'),
        main = getEl('main'),
        footer = getEl('footer');
  
  try {
    header.style.width = footer.style.width = `${main.clientWidth}px`;
  } catch {
    console.error('Houston we have a problem, with your html elements.');
  }
})
* {
  margin: 0;
  padding: 0;
}

body {
  /* Use flex for a quick layout parent structure */
  display: flex;
  flex-direction: column;
  justify-content: center;
}

header, main, footer {
    /* set the elements to center horizontally */
    margin: 0 auto;
}

main {
  display: flex;
  flex-direction: row;
  justify-content: center;
  /* comment out align-items if you want table of contents full height */
  align-items: flex-start;
  border: rgba(255,0,0,.25) 3px dashed;
}

article {
  max-width: 25rem;
}

nav {
  background: gray;
}

ul {
  margin-left: 1.5em;
}
<header id="header">...</header>
<main id="main">...</main>
<footer id="footer">...</footer>

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

A guide on updating div IDs using jQuery sortable when an element is moved by the user

My goal is to use jQuery sortable to allow users to rearrange elements on a page by dragging and dropping them. Each div element has a unique ID, and when the user swaps elements, I want to update the IDs accordingly and alert the new order so it can be sa ...

What is the method to retrieve text from a div element with Webdriver-IO?

Is there a way to extract the value from the following HTML element using Webdriver-IO for automated testing? <div class="metric-value ng-binding" ng-style="{'font-size': vis.params.fontSize+'pt'}" style="font-size: 60 ...

When it comes to identifying a click outside of an element, the Jquery or Javascript function may encounter some challenges specifically with Internet Explorer

After reviewing various solutions online, I noticed that they all function properly on Chrome and Firefox but encounter issues with Internet Explorer when interacting with an SVG. For instance, consider the following code snippet: $(document).on("click",( ...

The show/hide toggle button is malfunctioning and not functioning properly

I'm still learning jQuery and I attempted to create a show/hide toggle button without relying on jQuery's toggle function. However, I can't seem to identify the issue in the code below. Although the Hide button successfully hides the paragr ...

When the mobile navigation bar is tapped, it remains open instead of closing

The persistent challenge of the mobile navbar failing to close upon clicking an item continues to baffle. Numerous attempts from Stack Overflow and even tweaks recommended by ChatGPT have been futile in resolving this issue. Despite trying alternative me ...

Sometimes, IE8 fails to load CSS files properly

This issue is really frustrating me, guys The website displays correctly in Firefox and IE9, but has minor layout problems in Chrome and mobile Safari. When trying to load the page from the server in IE7 or IE8, it's very unreliable. It usually work ...

What is the best way to maintain the position of components (such as a Card component) when one is expanded in a Material-UI and ReactJS project

Currently, I am working with an expandable Card component from Material-UI and using flex for aligning the components. However, when one card expands, it affects the positioning of the other components in the row: https://i.stack.imgur.com/vGxBU.png What ...

Filtering and selecting tables in HTML

I am dealing with an HTML table that combines static data and MySQL input. The filtering functionality is working properly, but I am struggling to add the options "yes" and "no" to the selection list. These values are test inputs fetched from MySQL. I need ...

Issues with alignment in Bootstrap CSS

I have Bootstrap downloaded and the following code snippet. <header id="top"> <div class="container"> <div class="row"> <div class="col-sm-3 "> <image alt="here will be th ...

Replacing values in an HTML file with MySql query results

----- Problem solved, solution below ----- In my HTML file, I have a dropdown menu for various courses listed as follows: <ul> <li class="dropbtn" id="1"> <a href="">first</a> <ul class="dropdown-content"> ...

Update a designated div section on the webpage every 10 seconds

I have two pages, chat.php and allchat.php. I have successfully been able to load the allchat.php page into the chat.php div after a 10-second interval using the following code: $(document).ready(function(){ setInterval(function() { $( ...

What is the best way to display a particular JavaScript variable in an HTML document?

Is there a way to display the value of a Javascript variable in an HTML form, such as showing it on the screen? Below is my JavaScript code: <script type="text/javascript"> var howLongIsThis = myPlayer.duration(); </script> The variable howL ...

Discover how to determine the direction of a div element when utilizing the dir="auto" attribute in HTML5 with JavaScript

I'm experiencing an issue with a div that has the dir attribute set to auto. My goal is to retrieve the rendered direction using javascript After attempting div.dir, I only receive the 'auto' value. Is there a method available to detect if ...

Creating a scrollable nested div on a mobile website

Is there a way to achieve a scrollable nested div on a jQuery mobile site? I am aiming for a fixed header and footer with the middle section being scrollable. Despite my attempts to set overflow:scroll (along with specifying the width and height of the div ...

The HTML image tag is malfunctioning on a Windows system

I'm currently updating an HTML page and trying to add an image using the img tag. <img src="file:///C:/wamp/www/images/Sat.png" class="img-circle" alt="User Image"/> However, it doesn't seem to be working! ...

Can you provide a guide on how to retrieve an HTML file using JSON?

There is a problem with fetching files in different formats. Specifically, I want to retrieve an HTML file that needs to be embedded in an iFrame. Currently, my AJAX request only retrieves SWF files. Is there a way to call and fetch the HTML file instead ...

Issue with Bootstrap dropdown functionality when used in conjunction with typical JS and CSS implementations

When it comes to front-end development, I feel lost and confused. Recently, I tried to create a Bootstrap dropdown menu that appears upon clicking an anchor tag using the following HTML: <div class="dropdown"> <a data-target="#" class="dropdo ...

Simple steps to manipulate HTML content within a span element using JavaScript

I'm currently working on an online bus seat booking system and I've hit a roadblock with one feature. When a user selects more than one bus seat, the corresponding seat numbers should be displayed in a span or div, separated by commas. If the use ...

Steps to create interconnected circles using CSS

Currently, I am attempting to create a set of steps using only CSS. Here is what I have achieved so far: https://i.sstatic.net/sCRzr.jpg However, I am facing an issue with removing the excess line where the red mark is located. <ul class="step&q ...

How can I center align text after floating ul li elements to the left?

When creating a navigation bar with li elements floated left, the text also floats left. How can I center the text in the navigation bar? I have tried using text-align:center;, but it doesn't center the text on the y-axis. Some suggest using padding t ...