Is it possible for me to position an element beside the element before it?

Imagine a traditional layout consisting of paragraphs grouped with a sidebar. However, there are two issues with this setup: first, the browser displays the sidebar (typically used for navigation) before the main content, causing problems for screen readers and text-based browsers. To address this accessibility concern, the sidebar should be positioned after the article. This complicates using the common float:right technique, as absolute positioning can lead to further complications. The second issue is tied to the first; on narrower screens, I don't want the sidebar to sit alongside the text but rather appear below it.

Is there a way to achieve the same visual layout while swapping the positions of the two elements: #main and #sidebar?

#main {
  width: 100%;
}
#sidebar {
  width: 150px;
  height: 200px;
  background-color: #abc;
  float: right;
}
<div id="sidebar"></div>
<div id="main">
  <p>Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy...</p>
  <p>It is a long established fact that a reader will be distracted by the readable content of a page when looking at its layout...</p>
</div>

Answer №1

If you know how to utilize FlexBox, you can easily use the order property to change the order of elements.

I have already implemented it for you:

.wrapper {
  display: flex;
}

#main {
  width: 85%;
}

#sidebar {
  width: 150px;
  background-color: #abc;
  order: 1;
}
<div class="wrapper">
  <div id="main">
    <p>Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s, when an unknown printer took a galley of type and scrambled it to make a type specimen book. It
      has survived not only five centuries, but also the leap into electronic typesetting, remaining essentially unchanged. It was popularised in the 1960s with the release of Letraset sheets containing Lorem Ipsum passages, and more recently with desktop
      publishing software like Aldus PageMaker including versions of Lorem Ipsum.</p>
    <p>It is a long established fact that a reader will be distracted by the readable content of a page when looking at its layout. The point of using Lorem Ipsum is that it has a more-or-less normal distribution of letters, as opposed to using 'Content
      here, content here', making it look like readable English. Many desktop publishing packages and web page editors now use Lorem Ipsum as their default model text, and a search for 'lorem ipsum' will uncover many web sites still in their infancy.
      Various versions have evolved over the years, sometimes by accident, sometimes on purpose (injected humour and the like).</p>
  </div>
  <div id="sidebar"></div>
</div>

Preview

https://i.sstatic.net/8Yi4y.png

Answer №2

My approach to creating a float layout involved floating the first item to the left and then floating the second item to the right in a row. By doing this, I was able to place the #main element first in the markup and assign it a percentage width. Since the #sidebar had a fixed width, I had to use a media query to adjust its layout when it no longer fit on the same row. In such cases, I simply removed the floats to reorganize the layout. Assuming there were no other elements above or below these two, the process was relatively straightforward. The media query I used set a max-width of 408px, but this value may vary depending on your webpage.

#main {
  width: 60%;
  float:left;
}
#sidebar {
  width: 150px;
  height: 200px;
  background-color: #abc;
  float:right;
}

#main p {margin-top:0;}

@media screen and (max-width:408px) {
  #main {
    float:none;
  }
  
  #sidebar {
    float:none;
  }
}
<div id="main">
  <p>Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s, when an unknown printer took a galley of type and scrambled it to make a type specimen book. It has survived not only five centuries, but also the leap into electronic typesetting, remaining essentially unchanged. It was popularised in the 1960s with the release of Letraset sheets containing Lorem Ipsum passages, and more recently with desktop publishing software like Aldus PageMaker including versions of Lorem Ipsum.</p>
  <p>It is a long established fact that a reader will be distracted by the readable content of a page when looking at its layout. The point of using Lorem Ipsum is that it has a more-or-less normal distribution of letters, as opposed to using 'Content here, content here', making it look like readable English. Many desktop publishing packages and web page editors now use Lorem Ipsum as their default model text, and a search for 'lorem ipsum' will uncover many web sites still in their infancy. Various versions have evolved over the years, sometimes by accident, sometimes on purpose (injected humour and the like).</p>
</div>
<div id="sidebar"></div>

Answer №3

To achieve the desired layout, one option is to create a faux float element using a pseudo-element before, and then utilize absolute positioning to overlay the sidebar on top of it.

#main {
  width: 100%;
}
#main:before {
 content:'';
 float:right;
 background:red;
 width:150px;
 height:200px;
}
#sidebar {
  width: 150px;
  height: 200px;
  background-color: #abc;
  position:absolute;
  top: 16px;
  right: 8px;
}
<div id="main">
  <p>Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s, when an unknown printer took a galley of type and scrambled it to make a type specimen book. It has survived not only five centuries, but also the leap into electronic typesetting, remaining essentially unchanged. It was popularised in the 1960s with the release of Letraset sheets containing Lorem Ipsum passages, and more recently with desktop publishing software like Aldus PageMaker including versions of Lorem Ipsum.</p>
  <p>It is a long established fact that a reader will be distracted by the readable content of a page when looking at its layout. The point of using Lorem Ipsum is that it has a more-or-less normal distribution of letters, as opposed to using 'Content here, content here', making it look like readable English. Many desktop publishing packages and web page editors now use Lorem Ipsum as their default model text, and a search for 'lorem ipsum' will uncover many web sites still in their infancy. Various versions have evolved over the years, sometimes by accident, sometimes on purpose (injected humour and the like).</p>
</div>
<div id="sidebar"></div>

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

Calculating the width of fluctuating DOM elements in AngularJS

It seems like most of my Angular questions are just me overlooking something really silly, so let's hope that's the case here too. Currently, I am working on a directive to manage the scrolling of a wide list of thumbnails. While it was working ...

Modify the placeholder color for a disabled Input element to match the overall Mui theme design

I am struggling to change the color of the placeholder text in a disabled input field within my app's theme. Despite attempting to target the MuiFormControl, MuiInputBase, and MuiInput components in my theme.tsx file on CodeSandbox, I have not been su ...

Issue encountered with sortable table in list.js

Encountering a puzzling error while implementing list.js and tabletop for a sortable table sourced from a Google Doc. The error message reads: "Uncaught TypeError: Cannot read property 'childNodes' of undefined," pinpointing the first line in lis ...

Error message occurs when attempting to use the ->num_rows function on inner join statement and accessing a property of a non-object

I am attempting to fetch both Product_Name from the product table and Order_Date from the order table, but I keep encountering an issue at line 35 mentioning the "num_rows line". <?php $servername = "localhost"; $username='root'; $password = ...

Retrieve the selected date from the date picker widget

Welcome to my custom datepicker! Here is the HTML code: <div class="field-birthday field-return" id="birthday-edit" style="display:none;"> <div class="birthdaypicker"></div> <input class="hidden" name="birthday" type="hidden" ...

Reorganize elements using CSS styling

I have a trio of child divs with the classes span2, span7, and span3. When my browser width drops below 763px, I want them to display in the order span2, span3, and span7. How can I achieve this using CSS? Here is the code snippet I started with: <div ...

The AJAX data variable fails to send to PHP script although $_POST is defined

I am at my wit's end with this problem. I am attempting to send a variable to a PHP script using AJAX, and although I can confirm that $_POST is set, the variable remains undefined. Oddly enough, I have used almost the same code in other instances an ...

The event is being triggered on two separate occasions

Hey there! I'm trying to bind the onclick event to both a parent and child element using the same method. However, I'm running into an issue where the event is being fired twice. Any suggestions on how to prevent this from happening? <div id= ...

How can I prevent Chrome from constantly prompting for permission to access the camera?

I have been working on some HTML/JavaScript/WebRTC projects that involve using the webcam. Despite hosting the files from my local web server (127.0.0.1), Chrome always prompts me for permission to access the camera each time I reload the page. Is there a ...

Encountering difficulties accessing XML file on server via anchor tag

I have an XML file on the server that I am attempting to open in a browser when the user clicks on a link. Below is how I have set up the link, but it is not opening the file: Code: <a title="View XML" href="file://///90.0.0.15/docmgmtandpub/PublishD ...

Select dropdown in AngularJS for Date formatting

After retrieving json data from a web API, I found that it contains a series of datetimes. My goal is to select a specific datetime from a dropdown list. While I can populate the list without any issues, the formatting appears to be incorrect and I'm ...

What is the best way to increase the height of an image beyond the limits of its container, causing it to overlap with other elements

My challenge involves creating a horizontal scrolling list of movie posters. I want the posters to grow in size when hovered over, expanding outside of their container and overlapping other elements. I attempted to use 'position: absolute' on the ...

Is it possible to modify the class attribute of an HTML element in PHP upon clicking an input?

In this assignment, I am restricted to using only PHP and cannot incorporate JavaScript. Currently, my code is set up to detect a post from an input type="submit" and then check for empty or filled text inputs. The code currently echoes text based on the c ...

A step-by-step guide to invoking a function upon submitting a form with an external JavaScript file

How can I execute a function when the user submits a form using an external JavaScript file? index.html <!DOCTYPE html> <html> <head> <meta charset="utf-8"> <title>example</title> ...

Determine if I'm actively typing in the input field and alter the loader icon accordingly with AngularJS

Just delving into the world of AngularJS and attempting to tweak an icon as I type in an input box. Currently, I can detect when the box is focused using the following code: $scope.loading = false; $scope.focused = function() { console.log("got ...

The clip-path in Div: Css is malfunctioning and not displaying correctly

I am trying to create a chat bubble using CSS with rounded corners and a bottom-right arrow. However, I am having trouble getting the arrow to display correctly. https://i.stack.imgur.com/gVXOV.png The CSS styling for the chat bubble is as follows: ...

Tackling the sticky header problem with in-browser anchoring and CSS dynamic height restrictions

I am experimenting with a unique combination of a Pure CSS in-page anchoring solution using scroll-behavior: smooth and scroll-margin-top settings, along with a sticky header for in-page navigation. By utilizing IntersectionObserver, I can identify when t ...

Material UI causing animation to fail to trigger

After integrating material UI into my existing application, I encountered a peculiar issue. When adding material UI components to modals, the entering animation fails to trigger. Interestingly, downgrading material UI or removing all MUI components resolve ...

A straightforward guide on utilizing data-attributes to achieve a linear-gradient background

considering the following input .prettyRange { -webkit-appereance: none; } .prettyRange::-webkit-slider-runnable-track { background: -webkit-linear-gradient(right, #fff 0%, green 50%, #fff 0%); } <input class="prettyRange" type="range" name="cap ...

What are the steps to design a versatile gallery page that can serve various projects?

Allow me to get straight to the point. What is my goal? I am aiming to develop galleries for various projects. Each project's thumbnail on the main page should open a gallery as a new page. These galleries will all have the same layout but different ...