Is there a way to keep left-aligned text centered even when it wraps around?

I would like to center a block of left-aligned text within a div, ensuring that the visual width of the text block is centered rather than the block itself.

In situations where the div is narrow and the text is too long to fit on one line, causing it to overflow, this discrepancy becomes apparent.

Although I have displayed the text block as light blue for demonstration purposes in the examples below, in reality they will match the color of the parent div (white) with no line breaks.

In scenario 1a, the text fits within one line and is smaller than the maximum width of the text block, allowing me to set the width of the text block accordingly without any issues.

In case 2a, however, the text exceeds the maximum width and wraps onto the next line. This results in the visible text block appearing off-center.

How can I achieve both scenarios shown as 1b and 2b only using HTML and CSS?

Edit 1: Despite several suggestions on how to replicate the situation in 1a and 2a, my focus lies on accomplishing the layout seen in 1b and 2b.

Edit 2: The code I'm utilizing closely resembles David's example link (http://jsfiddle.net/davidThomas/28aef/). The use of text area colors is purely illustrative; changing it to white (http://jsfiddle.net/28aef/2/) highlights the issue where the margins are unequal.

Answer №1

Although this solution may be considered outdated, I recently encountered the same issue and found that none of the existing solutions were effective. While I cannot guarantee its compatibility across all browsers (as I have not conducted extensive testing), it did work for me!

The downside is that you will need to manually insert line breaks, but it appears to be a necessary step in resolving this particular type of problem.

Click here to view the solution

div.textContainer {
    text-align: center;
    border: 1px solid #000;
    height: 100px;
    padding: 10px 0;
}

div.textContainer p {
    display: inline-block;
    text-align: left;
}

Answer №2

It's possible that the original poster no longer has this issue, but I also had the same question and went searching for an answer. Below is what I discovered.

Please note: I am not an expert in this area, and there may be better ways to handle this situation. However, the solution I found worked for my application and may help others as well.

<div style = "text-align: center; margin-left: 10%; margin-right: 10%">
    <div style = "display: inline-block; text-align: left;">
        Insert desired text here.
    </div>
</div>

Keep in mind that the first div may not be necessary, and you can adjust the margins within the second div with minimal changes. Customize the percentages or specify a pixel width as needed. Hopefully, this saves someone time in the future without causing any new issues. Good luck!

Answer №3

Although this may be an older solution, it remains unanswered. By utilizing the calc() function and viewport units (vh and vw), along with some mathematical calculations, achieving centering can be done effectively. The key is to manually adjust the left and top positions to center the content. In my approach, I opted for viewport units due to their precision and dynamic nature.

.clr{ clear:both; }
.bg666{ background:#666;}  
.bgf4{ background: #f4f4f4; }
.hv60{ height: 60vh; }
.hv50{ height: 50vh; }
.wv60{ width: 60vw; }
.wv50{ width: 50vw; }
.tlset{ position:relative; left: 30px; top: 30px; }
.true_cntr_inner { position:relative; left: calc(60vw - 50vw - 5vw); top: calc(60vh - 50vh - 5vh); }
<div class='clr wv60 hv60 bg666 tlset'>
<div class='clr wv50 hv50 true_cntr_inner bgf4'>
this text spans across 50% of the viewport. It may seem obvious, but clarity is essential. 
Mistakes happen, just like bad spelling, so a little forgiveness goes a long way.
</div>
</div>

In my search for a way to center and resize a text-containing DIV on window resize, I stumbled upon this post. After encountering challenges with the standard CENTER method, I found a workaround that suited my needs. Hopefully, this solution proves helpful to others facing similar obstacles.

Answer №4

After exploring additional workarounds to the initial solution mentioned in the question, I came across two more alternatives that are somewhat suboptimal. To provide further assistance, I have compiled them along with a visual comparison for reference. One advantage of these alternatives is their compatibility with wrapped text and they do not rely on JavaScript.

  1. text-align: text-align: justify; — although effective, it may result in unsightly gaps between words, especially noticeable in short texts containing long words.
  2. hyphens:
    -webkit-hyphens: auto; -moz-hyphens: auto; -ms-hyphens: auto; hyphens: auto;
    — this option falls short in fully addressing the pseudo-right-margin issue.
  3. word-break: word-break: break-all; — while centered, it breaks words immediately upon reaching the edge.
  4. A combination of the above options can be considered for a more tailored approach.

To handle words exceeding the container's limits, adding overflow-wrap: break-word; becomes necessary. The reason why this was left as a comment was to demonstrate how each method handles lengthy "syllables" differently. It's important to note that no hyphen is included, similar to word-break: break-all;.


  • The inspiration for some of these solutions was drawn from the website justmarkup.com.

  • If manual <br> insertion is acceptable, then John's response may be more suitable.

  • If utilizing JavaScript is an option, refer back to my previous comment or explore the provided link, if desired.

  • I had also mentioned CSS media queries as a potential solution alongside JavaScript. However, after reviewing them, it seems unlikely that they would be effective in this scenario. They depend on predictable content sizes to calculate the container's dimensions in advance. Essentially, they monitor the viewport's size to adjust the container based on preset criteria, which isn't applicable when dealing with unpredictable text lengths.

  • Container queries offer no resolution as they lack the ability to assess text width directly, only the box housing it. Setting display: contents to prevent the creation of said box results in a width of 0px.

  • An ongoing challenge has been highlighted in a recent Chrome blog post concerning text balance. The acknowledgement of this issue by Google Chrome showcases awareness, indicating that similar techniques could potentially address the problem:

. . .

The irony of balanced text wrapping leading to imbalance within the enclosed element.

A brief overview of the browser's methodology

By employing a binary search strategy, the browser seeks the narrowest width without causing line breaks, refining to one CSS pixel (not display pixel). To expedite the process, the initial step corresponds to 80% of the average line width.

div {
  width: 10em;
  margin: 0 auto 1em auto;
  border: 1px solid #000;
  padding: 1em;
  background-color: lightgreen;
  /* overwritten in case 0 */
  
}

.text0 {
  text-align: justify;
}

.text1 {
  -webkit-hyphens: auto;
  -moz-hyphens: auto;
  -ms-hyphens: auto;
  hyphens: auto;
}

.text2 {
  word-break: break-all;
}

h1 {
  text-align: center;
}

p {
  background-color: aqua;
  /*overflow-wrap: break-word;*/
}
<!DOCTYPE html>
<html lang="en">
<!-- !DOCTYPE and html tags are required for the hyphens to work in this example -->

<body>
  <h1>Justify</h1>
  <div class="text0">
    <p>This is a bit of text displaying on more than two lines. Try to bbbbbbbbbbbbbbbbbbbbbbbreak this word.</p>
  </div>

  <h1>Hyphens</h1>
  <div class="text1">
    <p>This is a bit of text displaying on more than two lines. Try to bbbbbbbbbbbbbbbbbbbbbbbreak this word.</p>
  </div>

  <h1>break-all</h1>
  <div class="text2">
    <p>This is a bit of text displaying on more than two lines. Try to bbbbbbbbbbbbbbbbbbbbbbbreak this word.</p>
  </div>
  
  <h1>Justify and break-all</h1>
  <div class="text0 text2">
    <p>This is a bit of text displaying on more than two lines. Try to bbbbbbbbbbbbbbbbbbbbbbbreak this word.</p>
  </div>
  
  <h1>Justify and hyphens</h1>
  <div class="text0 text1">
    <p>This is a bit of text displaying on more than two lines. Try to bbbbbbbbbbbbbbbbbbbbbbbreak this word.</p>
  </div>
</body>

</html>

Answer №5

Consider using Flexbox for layout:

  .d-flex {
      display: -ms-flexbox;
      display: flex;
  }
  .flex-column {
      -ms-flex-direction: column;
      flex-direction: column;
  }
  .ml-auto, .mx-auto {
      margin-left: auto;
  }
  mr-auto, .mx-auto {
      margin-right: auto;
  }
  .w-50 {
      width: 50%;
  }
<div class="d-flex flex-column mx-auto w-50">
  <p>Left aligned text</p>
  <p><em>Lorem ipsum dolor sit amet, consectetur adipiscing elit. Phasellus volutpat justo et vehicula tristique. Vestibulum nec mi turpis. Fusce ultrices velit at odio malesuada sagittis.</em></p>
  <p>Using <a href="https://getbootstrap.com/docs/4.1/utilities/flex/">Bootstrap 4</a> classes.</p>
</div>

Answer №6

<div style="text-align:center;">
    <div style="display:inline; text-align:left; margin:20px;"> <!-- Custom width can be specified here for the block -->
          Your content goes here
     </div>
</div>

In this code snippet, the first div acts as a container with center alignment applied.

Within the inner div (blue area), we maintain inline display, left text alignment, and add a specific margin to control white space around the text when wrapping occurs.

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

The secret to achieving perfectly even spacing along the vertical axis

I'm working on a card design that contains a div with 3 elements - 2 headers and a paragraph. I need to ensure there is consistent spacing between each element and the top/bottom of the card. Currently, there seems to be too much margin after the last ...

Engage the PROTRACTOR refresh function

I'm just getting started with automation and Protractor. I successfully automated the login page, but now I'm facing a challenge with accessing a menu that I need in order to navigate to a different page. Within the menu, there is an href="#/dom ...

Choosing an element with JavaScript

var displayedImage = document.querySelector('.displayed-img'); var thumbBar = document.querySelector('.thumb-bar'); btn = document.querySelector('button'); var overlay = document.querySelector('.overlay'); /* Itera ...

How to transfer data from local storage to PHP using Ajax

Is there a way to pass values from JavaScript to PHP that are stored in local storage? JavaScript let cartItems = localStorage.getItem("productsInCart"); var jsonString = JSON.stringify(cartItems); $.ajax({ url:"read.php", method: "post", da ...

What is the best method for closing the open portion of an accordion menu?

I'm experimenting with creating a collapsible accordion feature, but I'm facing a challenge in figuring out how to close the currently open accordion pane. The accordion functions smoothly when expanding sections, but I'm stuck on how to col ...

I'm experiencing an issue with the sub-menu disappearing and preventing me from clicking on any links

Currently, I have set up a navigation bar with a sub-menu that spans the full width of the page. When hovering over the list items, the sub-menu appears as expected. However, when moving the mouse down into the sub-menu, it disappears instantly. The object ...

Converting Uniquely Designed Photoshop Shapes into HTML

I am working on a project to design an HTML page that features a profile picture with a heart frame. I have the PSD file with the heart frame included. The profile pictures will be rectangular in shape and should fit behind the heart frame without overlap ...

Ensuring that Bootstrap rows fill the entire height within a column

While working on a template with nested rows and columns in Bootstrap, the layout ended up looking like this: <div class="col-5"> <div class="row"> <div class="col-3 border border-secondary">Truck Number</div> ...

Stylish Radial Hover Effect for Images Using CSS

I am looking to create a unique effect where upon hovering over an image, color will be applied in a radial shape on a grayscaled image within a div that is pointed by the cursorhttps://i.sstatic.net/64RJv.jpg Below you can see the desired outcome compare ...

Creating a webpage with a left panel and draggable elements using JavaScript/jQuery

As someone new to Javascript/jQuery, I have been given the task of creating a web page with elements in a "pane" on the left side that can be dragged into a "droppable" div area on the right side. The entire right side will act as a droppable zone. I am u ...

showing text style that is only specified on the server, not by the client

I am in the process of creating a new website that offers SMS services through clickatell. This website includes various font families that may not be defined on the client's computer. For instance, if the site is accessed from a different computer, t ...

Semantic UI (React): Transforming vertical menu into horizontal layout for mobile responsiveness

I have implemented a vertical menu using Semantic UI React. Here is the structure of my menu: <Grid> <Grid.Column mobile={16} tablet={5} computer={5}> <div className='ui secondary pointing menu vertical compact inherit&apos ...

What is causing the page to not load in my development environment (MAMP PRO) when using header()?

Has anyone experienced the issue where suddenly on MAMP PRO, the page will only load up to the header() function? For example, here is a header call I am using: header('Location: /index_signedIn.php'); exit(); I have tested my other sites and ...

Add bullet points to the events listed in fullcalendar

Currently, I am implementing the 'fullcalendar' plugin from jquery in order to display events for a specific month. I am interested in adding bullets to the events, however, my online search did not yield any relevant results. Although I am awar ...

Using various class names with the :first-child selector

I need help styling the first item of a HTML structure I have: <div class="home-view"> <div class="view-header">Header</div> <div class="view-content">Content</div> </div> In this structure, I want to style t ...

"The printing function of the "Print page" button appears to be malfunctioning

I am having some trouble with my JavaScript code for a "print page" button in an HTML document. The button appears and is clickable, but it doesn't actually print the page as intended. I keep receiving 3 errors related to the `document` object being u ...

What is the best way to loop through <div> elements that have various class names using Python 3.7 and the Selenium webdriver?

I am currently in the process of creating a Reddit bot that provides me with a detailed report about my profile. One task I need to accomplish is identifying which of my comments has received the most likes. Each comment on Reddit is wrapped in elements w ...

Utilizing Bootstrap divs for multiline display in Yii2 platform

Currently, I am utilizing a list in Bootstrap CSS which is responsive and beneficial. However, I am faced with the challenge of creating a notification list with lengthy text akin to that on Facebook. My query pertains to the technique required to make th ...

Access a folder in JavaScript using Flask

I need to specify a directory in a script. $images_dir = '{{url_for('.../pictures')}}'; In my flask application directory structure, it looks like this: Root -wep.py -templates -gallery.html -static -pictures The images are stored ...

Map will be visible correctly only when the window is resized

I'm currently working on a project that utilizes a map engine from a private company which I am unable to disclose. The initial system was built in JQuery, but we recently underwent significant changes and now have it running on AngularJS. One side ...