Ensuring that the text snippet is positioned centrally inside a container

I am currently developing a dynamic slideshow feature.

My challenge is to ensure that any text I input dynamically is centered both horizontally and vertically within a designated box.

My current code snippet looks like this:

HTML

  <body>
  <div class="slide">
    <span class="content">
       <b>Hello. This text should be:</b><br><br> 
       - left-aligned but <br>
       - centered in the grey box<br> 
       - even if it changes<br>
       - the center of the white box <br> 
         should match the center of the grey one.
    </span>
  </div>  
  </body>

CSS

.slide {
  position:relative;
  background-color: #ddd;
  width: 300px;
  height: 300px
}

.content {
  position: absolute;
  top: 30%;
  left: 15%;
  background-color: #fff;
}

OUTPUT

The current implementation does not perfectly center the text, especially if the content changes. Does anyone have suggestions on how to improve this?

http://jsbin.com/uyiFiwI/23/edit

Answer №1

This accomplishes the desired outcome, however, it hinges on the use of display: table-cell, a property that is not compatible with older web browsers.

.slide {
  position:relative;
  background-color: #ddd;
  display: table-cell;
  width: 300px;
  height: 300px;
  text-align: center; 
  vertical-align: middle;
}

.content {
  background-color: #fff;
  display: inline-block;
  width: auto;
  height: auto;
  margin-left: auto;
  margin-right: auto;
  text-align: left;
}

I haven't come across a solution that caters to older browsers without altering the HTML structure.

EDIT: It's unnecessary to specify a fixed height for .content.

EDIT: The border: 1px solid gray style, initially used for debugging purposes, has been removed.

EDIT: Updated based on @Shomz's recommendation, introducing new and varied criteria for the width of .content.

Answer №2

For a versatile solution that will work well in any situation, consider this CSS styling for your slide:

div.slide {
  position:relative;
  background-color: #ddd;
  text-align: center;
}

div.content {
  text-align: left;
  position: relative;
  display: inline-block;
  margin: 10% auto;
  background-color: #fff;
}

http://jsbin.com/uyiFiwI/28/edit

If your .slide div requires a fixed height, you may need to utilize JavaScript to accurately calculate the height of the content div, or experiment with CSS workarounds that may not be universally supported across all browsers, as mentioned by @David.

Answer №3

If you're open to tweaking your markup slightly, utilizing a list format can assist in tidying up any line breaks and spacing issues.

Implementing this in conjunction with display: table-cell similar to @David-SkyMesh's suggestion can result in a list format that is easier to manage.

HTML

  <div class="slide">
    <div class="content">
      <b>Hello. This text needs to be:</b>
      <ul>
        <li>left-aligned but</li>
        <li>centered in the grey box</li> 
        <li>even if it changes</li>
        <li>the center of the white box this this is really long text not the gray one should equal center of grey one.</li>
      </ul>
    </div>
  </div>  

CSS

.slide {
  position:relative;
  background-color: #ddd;
  width: 300px;
  height: 300px;
  padding: 20px;
  display: table-cell;
  vertical-align: middle;
  text-align: center;
}

.content > ul > li:nth-child(1) {
  margin-top: 10px;
}

.content {
  display: block;
  margin: auto;
  background-color: #fff;
  text-align: left;
}

.content ul {
  margin: 0;
  padding: 0;
  padding-left: 20px;
}

Demo - jsBin

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

I am having trouble getting the jsTree ajax demo to load

I am having trouble running the basic demo "ajax demo" below, as the file does not load and the loading icon continues to churn. // ajax demo $('#ajax').jstree({ 'core' : { 'data' : { ...

Utilizing BeautifulSoup to Extract Links

Currently, I am extracting cricket schedules from a specific website using Python's Beatiful Soup library. The webpage I am scraping corresponds to the following URL: www.ecb.c0.uk/stats/fixtures-results?m=1&y=2016 This particular link displays ...

Using jQuery to update the CSS background of a selected element among multiple elements sharing the same class

I am currently developing a basic jQuery script that will enable the background color of the clicked element to change. Below is the code I have so far: <dt> <input id="p_method_banktransfer" value="banktransfer" type="radio" name="payment[metho ...

How can I position text next to an input within a <td> element in a vertical arrangement?

Below is the HTML code: <fieldset><legend>Callout Report</legend> <table> <tr><td>Start Time</td><td> <input type="text" id="startTimeUI" autocomplete="off" /> </td></tr> <tr><td& ...

Adjust the transparency of a `<ul>` element as it descends on the webpage - CSS3

I have a list (<ul>) that I would like to fade out as it scrolls down the page. I attempted to use linear-gradient, but I was unsuccessful. Is this even possible? You can view an example of what I am trying to achieve on JSFiddle here: http://jsfidd ...

Tips on placing an li element into a designated DIV

Just starting out with jquery and working on a slider project. Here's what I have so far: <ul> <li> <img src="image.jpg"><p>description of the current image</p></li> <li> <img src="image.jpg"> ...

Employing ngModel in an option dropdown

I am having trouble passing an attribute from an API call to a submit function. I suspect it might have something to do with either the option select or how the input is being formatted. Encountering the error Error: No value accessor for form control wit ...

Unable to display the content

Why isn't the text expanding when I click "see more"? Thanks XHTML: <div id="wrap"> <h1>Show/Hide Content</h1> <p> This code snippet demonstrates how to create a show/hide container with links, div eleme ...

What steps should I take to ensure that my dropdown menu functions properly?

I am struggling to get my navigation bar with dropdown menus to function properly. I suspect there might be an issue with the CSS code. Can you take a look at it? Here is the HTML code snippet: /*---------------------NAVBAR-------------------*/ ...

clear the input field of any entered text type

Just starting out with Javascript! Below is some code: This code is taken directly from the HTML page <form action="#" id="ToolKeywordSearch"> <input type="text" class="ProductFinderText" id="ToolSearchField"onblur="if(this.value==& ...

Issue with binding background images to DIV elements in Angular 4 CSS

Here is a template example: <div [style.background-image]="profileImage" ></div> In the TypeScript file: We declare private profileImage: any; and use DomSanitizer for security. Fetching photo from service: We set this.profileImage using b ...

Using javascript to locate and substitute a word divided among multiple tags - a step-by-step guide

I need to utilize JavaScript to locate and substitute a word that has been separated into multiple tags. For instance, consider the following HTML code: <html> <body> <div id="page-container"> This is an apple. ...

What is the best way to separate the date and time into individual components?

I have created a dynamic object that shows both the date and time. My goal is to figure out how I can separate the time portion from the date so that I can place it in its own HTML element and style it differently? JavaScript isn't my strong suit, e ...

Tips for retrieving a selected date from an HTML textbox labeled as "Date"

My goal was to find the differences between two dates by utilizing an HTML Date textbox. <input type="text" name="datein" id="datein" value="" class="inputtexbox datepicker" style="display: none" is-Date/> <input type="text" name="dateto" id=" ...

Adding the target='_parent' attribute to the infowindow of a Google Fusion Map by utilizing a click event listener

As someone who is relatively new to Google Fusion, I am eager to expand my knowledge and skills. Recently, I created a customized map with an infowindow and embedded it onto my website using the FusionTablesLayer Wizard. I wanted to avoid using the target= ...

Achieve perfect vertical alignment for a set of three identical boxes using CSS media queries

Bootstrap is being used and the goal is to align three boxes of the same height vertically. https://i.stack.imgur.com/8xg0g.png Currently, the three blocks are not of equal height and do not occupy maximum space. Some manual padding has been added to addr ...

CSS not working when attempting to override Angular (13) Material file

In my Angular (13) application with Material, I have developed a CSS file specifically for overriding certain Material styles. This CSS file is imported into the styles.scss file as the last line. However, despite importing the external file, the CSS def ...

The Layout of Bootstrap4 Form is Displaying Incorrectly

I'm attempting to create a basic email form similar to the one shown in the Bootstrap 4 documentation. However, I am facing an issue where the formatting is not displaying correctly. Here is what the example should look like: https://i.sstatic.net/qx ...

The symbols ">>" have been changed to "�"

There has been a report from one of our application users stating that they are seeing the character � instead of >> on their home and other pages. This issue is only affecting one out of 100 users, and the user in question is using IE11. What c ...

CSS guidelines for layering shapes and divs

Currently, I am in the process of developing a screenshot application to enhance my understanding of HTML, CSS, and Electron. One of the key features I have implemented is a toggleable overlay consisting of a 0.25 opacity transparent box that covers the en ...