If the text is a single line, center it. However, do not center the text if it

Can we center align text horizontally if it occupies a single line, but refrain from center aligning and use white-space: normal when the text spans multiple lines (ideally without the need for JavaScript)?

Answer №1

Check out this solution using HTML and CSS.

Some key techniques to note:

  1. The <span> within the <p> tag has a property of display: inline-box;, allowing it to adjust its size based on content.

  2. The <p> tag is styled with text-align: center, resulting in the <span> being centered when its width is smaller than that of the <p>.

  3. The <span> has text-align: left, ensuring the alignment of the text inside.

<!DOCTYPE html> <html>
    <head>
        <title>Center</title>
        <style type="text/css">
            .big-box {
                text-align: center;
                width: 40em;
                border: 1px solid red;
            }
            .center-if-single-line {
                text-align: left;
                display: inline-block;
                border: 1px solid blue;
            }
        </style>
    </head>
    <body>
        <div>
            <h1>Small</h1>
            <p class="big-box">
                <span class="center-if-single-line">
                    All your line are belong to us!
                </span>
            </p>
            <h1>Big</h1>
            <p class="big-box">
                <span class="center-if-single-line">
                    All your line are belong to us! (Repeated multiple times)
                </span>
            </p>
        </div>
    </body>
</html>

Answer №2

To determine the best course of action based on the height of a div/p element in Javascript, you can check its height and adjust styling accordingly. Understanding the height of the DOM element for a single line will help guide your decision-making process. If the height surpasses this threshold, you can make one change; if it doesn't, you can make another. By setting your CSS to default to the more common scenario and modifying it only when necessary, you can ensure consistency.

Here's an example:

var tag = document.getElementById("id_here");

if(tag.offsetHeight > 18){
   tag.style.textAlign = "left";
   tag.style.whiteSpace = "normal";}

Alternatively, jQuery can also be used. Keep in mind that offsetHeight accounts for padding.

While a Javascript solution is viable, ideally you would want to avoid it. Finding a way to achieve this dynamically using CSS poses challenges. It may not be feasible to accomplish purely through CSS styles.

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

Arrange the table in alphabetical order and categorize it

Hello there! I am currently working on creating a well-organized table list where names are sorted into specific categories based on their starting letter. For example, names beginning with 'A' will be placed in the 'A category', while ...

How can I use HTML to replace specific text or blocks within the DraftJS Editor?

Incorporating Rich Text capabilities into my React-based web application using DraftJS Editor has been a focus of mine. One specific requirement I have is the ability for a user to trigger a drop-down menu by typing the "#" key next to the editor. From th ...

Having trouble accessing an element using jQuery(idOfElement) with a variable as the name parameter

Possible Duplicate: Issue with JavaScript accessing JSF component using ID Whenever I attempt to retrieve an element by passing a variable in jQuery(idOfElement), it doesn't work. But if I use something like jQuery('#e'), it works perfe ...

Troubleshooting: ngAnimate max-height failing to apply to specific element

Having integrated ngAnimate into a project to enhance animations, I've encountered some unusual behavior with a specific element. Let me provide some context: our website features a shop with categories and products within those categories. I am usin ...

Autosuggest Feature in Google Maps

Can someone please help me with customizing the width of the input text box and drop down menu using this resource: https://developers.google.com/maps/documentation/javascript/places#places_autocomplete? I'm having trouble figuring it out. ...

Production environment poses a challenge as Rails 4 struggles to locate fonts

Situation: I am facing an issue with my Rails 4.0.0 application deployed using capistrano, where the asset precompilation does not work properly on my production server. Challenge: Despite successfully adding a font and using it with @font-face locally, t ...

Responsive design not functioning properly for Bootstrap columns on website

If my display currently looks like this with three equally distanced images at the top and two images at the bottom, how can I achieve that design? I attempted using Bootstrap by setting the top 3 images as <div className="col-md-4"> and t ...

The presence of parentheses in a JQuery selector

My database contains divs with ids that sometimes have parentheses in them. This is causing issues with my JQuery selector. How can I resolve this problem? Let me provide an example to illustrate: https://jsfiddle.net/2uL7s3ts/1/ var element = 'hel ...

Stopping the WordPress gallery at the end without looping using Elementor

Is there a way to make my gallery stop at the end of the last picture without having to add any jQuery code? I inserted this gallery using elementor widgets and would appreciate your help on this matter. Additional information: Upon clicking on an image, ...

Modify the text color of the sliderInput element within a Shiny application

I am attempting to change the font color of the values (1,2,3,...10) in the sliderInput() from black to white, but I am encountering difficulties. How can I connect the slider with the CSS file to achieve this? ui <- fluidPage( tags$style(type = &quo ...

Analog Clock Time Adjustment Bubble Deviation Dilemma

Recently, I encountered an issue with an analog clock component. Every time I click on the time adjustment bubble repeatedly while also moving the cursor position, it tends to drift away from its original placement, which should ideally be between an orang ...

Designing a dynamic patterned backdrop that seamlessly extends for a column in bootstrap

Experiencing some difficulties with Bootstrap and creating a resizable column background. In one row, there is a column with a fluid image at the top, another column below it with a CSS class that gives it a repeating background along the Y axis, and fina ...

I'm searching for the HTML5 specifications and information on which browsers support specific features. Can you point me in the right direction

Where can I locate the HTML5 specifications for Internet Explorer, Opera, Firefox, and Google Chrome browsers? ...

Is there a way to open an HTML file within the current Chrome app window?

Welcome, My goal is to create a Chrome App that serves as a replacement for the Chrome Dev Editor. Here is my current progress: background.js chrome.app.runtime.onLaunched.addListener(function() { chrome.app.window.create('backstage.html', { ...

Guide to getting Material-UI Dialog up and running smoothly in your React application

I'm currently working on a project using material-UI, and I'm having trouble with the Dialog component not working properly. Despite trying various solutions, I haven't been able to get it to function correctly in my React application with m ...

Incorporate an XNA game directly into a website

Is it possible to launch an XNA game directly from a web page without the need for any installations? Something along the lines of Java, Silverlight, or similar to WPF Browser Applications (XBAP). Situation: Visit a webpage, Prompted to install the g ...

Zoom in to see the header spanning the entire width of the page

http://jsfiddle.net/CPSKa/ Whenever I zoom in on the header of my website, the line underneath it starts to shrink. Is there a way to prevent this from happening? Here is the HTML Code: <div id="main_header"> <div id="main_header_wrapper"&g ...

Utilizing React in conjunction with i18next and incorporating the HTML attribute lang

My website is built using React and i18next, with support for multiple languages. I am trying to change the 'lang' attribute in my HTML page. How can I achieve this? Even though I am using the i18next-browser-languagedetector, the lang attribut ...

Retrieve information from an HTML form

Currently, I have a piece of Javascript that fetches the HTML for a form from the server using an XMLHttpRequest and then displays the form on the page. I am looking for a solution to extract the data that would be sent via POST if the form were submitted ...

What steps can be taken to safeguard the title of the document in the top window from being altered by any iframe or script?

My typical approach is to delete and redefine the title property like in the code snippet below: if (delete document.title) { Object.defineProperty(document, 'title', { get: getter, set: setter, enumerable: true, ...