Positioning a div in the center horizontally may result in content with a large explicit width being

I am in search of a solution to horizontally center content on a webpage, regardless of whether or not it has a defined width.

After referencing a Stack Overflow question on centering a div block without the width, I found a great method that works well when the content has no specified width or if it's smaller than the containing area.

However, when the content's width exceeds that of the containing area, the content gets centered but becomes inaccessible for scrolling.

CSS:

.letterbox-outer-wrap {
    padding-top: 20px;
    position:relative;
    background: aqua;
    overflow:hidden;
}

.letterbox-outer-center {
    float:left;
    position:relative;
    left: 50%;
    background: yellow;   
}

.letterbox-inner-center {
    float: left;
    position:relative;
    left:-50%;
    background: red;
}

.letterbox-clear {
    clear: both;
}

.large-explicit-width {
    width: 3000px;
    background:purple;
}

HTML:

<div class="letterbox-outer-wrap">
    <div class="letterbox-outer-center">
        <div class="letterbox-inner-center">
            <p class="large-explicit-width">
Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.
            </p>
        </div>
    </div>
</div>

My question is, how can I center a div horizontally when its width is uncertain? And if the width surpasses the container size, I'd prefer the content to be left-aligned with a scrollbar at the bottom of the page, to function like a standard webpage.

Check out the jsfiddle for an example.

If necessary, I am open to incorporating JavaScript or jQuery for a solution.

Answer №1

Utilizing the left property for centering content may restrict overflow access. To achieve centering when the width is smaller than the browser size, consider the following code snippet:

.letterbox-outer-wrap {
   text-align:center;
}
.letterbox-outer-center {
  display:inline-block;
}

By removing the float and left properties, you can achieve the desired outcome. View the result at http://jsfiddle.net/s5TLz/1/

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

What is the best way to customize bootstrap styles?

Currently, I am attempting to modify basic CSS attributes within the default theme that is included with a new ASP.NET MVC 5 application in Visual Studio 2013. Specifically, my goal is to change the background color of the navigation menu. With the help o ...

Reviving jQuery Smooth Zoom Pan viewer following container resize

I am in the process of developing a responsive image viewer and have decided to incorporate the Smooth Zoom Pan plugin for enhanced pan/zoom functionality. Within my layout, I have two primary panels: the viewer container and a controls container that are ...

Generating directives on the fly

I am relatively new to AngularJS and have a good understanding of the basics. My goal is to create a desktop interface where items are loaded dynamically from a database using $http. I have already developed a directive that displays a title and an icon fo ...

Strategies for handling axios responses within a useEffect hook in Reactjs

Currently, I am working with Reactjs and implementing nextjs. I am facing an issue where I am using Axios for fetching data from an API, but I am struggling to display it on the page. To debug this, I have tried using console.log inside the useEffect fun ...

Dividing the logic from the Express router while retaining the ability to utilize Express functionalities

As I embark on my journey of developing my first app using Node.js and Express, I have noticed that my router file is starting to get overcrowded with logic. It seems like there is too much going on in there. My solution to this issue is to pass a functio ...

Tips for Uploading Large Images to Backend API in Next.js

As I work on building my portfolio using NextJS, I encountered an issue with the Project Functionality. When converting images to base64 and sending them to an API for uploading on Cloudinary, everything runs smoothly as long as the total size of the req ...

Retrieving distinct items from an array containing nested objects and sub-properties

In my script, I am attempting to retrieve unique objects based on the state from an array of objects. The current script is functioning correctly for most cases. However, there is one scenario where a nested object in a specific state has a sub-state, and ...

Steps for compiling SCSS to CSS using Angular-CLI and moving it to the assets directory

I am currently working on an Angular 5 project with an assets folder where I store my common CSS file and reference it in index.html. I now plan to create a new folder called "sasstyles" and place some .scss files there. When I compile or run the project ...

JavaScript TweenJS is a powerful library that simplifies

Hey there, it's my first time posting on Stackoverflow. I'm facing an issue with a tween in my code. It seems like the brute function is being called at the end, indicating that the tween should be running. However, I'm not seeing any actual ...

Can someone help me with combining these two HTML and JavaScript files?

I successfully created an HTML/JavaScript file that functions properly: <html> <head> <meta name="viewport" content="initial-scale=1.0, user-scalable=no" /> <script type="text/javascript" src="http://maps.google.com/maps/api/js?sensor ...

Can the default position of the scrollbar be set to remain at the bottom?

I have a select option tag with a scrollbar to view the contents in the dropdown. I am looking for a way to automatically position the scroll at the bottom when an item is selected from the dropdown. jquery code $('document').ready(func ...

Checking for the existence of a specific key in JSON data from the Twitter API using

Successfully fetching a tweet from the Twitter API is possible. Along with displaying the user, tweet, and other data, I also want to display the image. However, if there is no image attached to the tweet, nothing appears as the key doesn't exist. ...

Is there a way to remove a row through fetch using onclick in reactjs?

I'm completely new to this and struggling with deleting a row using fetch. I've written some messy code and have no idea if it will even work. Please help, I feel so lost... renderItem(data, index) { return <tr key={index} > &l ...

Selenium with Javascript

I am currently working on a website that utilizes the jquery.treeview.js plugin to display multiple nested branches. Each branch contains a JavaScript button: <a href="javascript:void(0);" id="show_link" class="show_links" onclick="$(this).parent().chi ...

Arrange items in a particular order

I need help sorting the object below by name. The desired order is 1)balloon 2)term 3)instalment. loanAdjustmentList = [ { "description": "Restructure Option", "name": "instalment", " ...

Creating a session using jQuery to maintain user data without having to refresh the entire

Struggling with setting a session using jQuery and AJAX without the need for a page refresh. Currently, I can only set the session by pressing the refresh button, which is less than ideal. My PHP page is separate from my jQuery code, making it challengin ...

Exploring the data types of dictionary elements in TypeScript

I have a model structured like this: class Model { from: number; values: { [id: string]: number }; originalValues: { [id: string]: number }; } After that, I initialize an array of models: I am trying to compare the values with the o ...

When attempting to upload multiple images to my backend, I am consistently receiving an empty array as a result

I have developed an API on the backend that is designed to store images in the database. I have implemented a function for uploading these images, but unfortunately, I am encountering an issue where my database receives an empty array. Interestingly, when ...

Generating interactive child posts for a specialized post type in WordPress

I am currently in the process of planning a simple plugin and am searching for ideas on how to add subposts (child) for posts in WordPress directly on the post creation page. I would like to incorporate a form with two fields, title and content, and have ...

What could be causing the server to return an empty response to an ajax HTTP POST request?

Attempting to make a POST request using ajax in the following manner: $.ajax({ type: "POST", url: 'http://192.168.1.140/', data: "{}", dataType: "json", ...