Is it true that when "text-align: center;" is applied to an element with absolute positioning, it has no effect on its child elements?

Let me show you the code first before explaining my issue:

Tinkerbin:

<style>
  div.container{
    height: 200px;
    width: 200px;
    background-color:red;
    margin-top: 10px;
  }

  div.subContainer{
    position: relative;
    text-align: center;
  }

  div.inner{
   position: absolute;
   background-color:yellow;
   width: 150px;
  }
</style>

<div class="container">
  <div class="subContainer">
    <div class="inner">bananas for breakfast</div>
  </div>
</div>

As per the textbook, when text-align: center; is applied to a parent element, it only centers its child elements if they have display: inline;.

Hence, since a <div> by default has display set to block (display:block;), the text-align: center; on the parent div.subContainer does not affect its child div.inner.

Everything seems fine until now. No surprises yet.

The problem arises when I replace <div> with <span> in the .inner element and position it absolutely (position: absolute;) - which changes its display from inline to block as you are aware.

Have a look:

<style>
  div.container{
    height: 200px;
    width: 200px;
    background-color:red;
    margin-top: 10px;
  }

  div.subContainer{
    position: relative;
    text-align: center;
  }

  span.inner{
   position: absolute;
   background-color:yellow;
   width: 150px;
  }
</style>

<div class="container">
  <div class="subContainer">
    <span class="inner">bananas for breakfast</span>
  </div>
</div>

The outcome is unexpected. Despite having the display value forced to block (due to position: absolute;), the span is still centered. Moreover, the alignment is peculiar. It aligns the left side of the block with the center of the containing element instead of centering both sides.

This behavior is rectified - starts acting like a block - when I manually set the display on span.inner to block.

span.inner{
   position: absolute;
   display: block;
   background-color:yellow;
   width: 150px;
}

So, what's causing this confusion? Shouldn't absolute positioning force a change in display to block? Why is the centering behaving strangely?

Answer №1

Once you designate it as position: absolute, it transforms into a block but is removed from the natural flow of content from its original placement. If you refrain from utilizing top, left, bottom, and right, this deviation becomes quite conspicuous.

When dealing with a <div>: A div, by default, behaves as a block-level component filling the entire available width. Consequently, it naturally commences at the left margin of the container and extends to the right edge. When positioned absolutely, it remains anchored at the top left corner where it was initially placed, with the only apparent distinction being in the width adjustment.

When working with a <span>: A span typically functions as an inline element influenced by the text-align attribute of its parent. The text cursor starts at the middle of the element, adjusting as new characters are added to maintain text alignment based on width. Upon removing the span from the regular flow, it shifts to the exact point where the text would have commenced. Now, the text cursor aligns precisely at the midpoint (horizontally) of the element without any accompanying text within the parent structure.

You've successfully identified the resolution: incorporating display: block will enforce the element to function as a block-level entity. Although, even though position: absolute may appear to "impose" this trait, it actually serves as a calculated value rather than an inherent property of the element. As such, it solely influences the element's positioning when explicitly defined within its CSS specifications.

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 position a div at the center between two other divs on the left and right?

My goal is to create a layout similar to THIS, with 3 buttons aligned in a row - one on the left, one in the center, and one on the right. I want to achieve this using CSS and divs instead of tables. I have managed to position the left and right buttons c ...

Is it a:first-child or a:first-child aside?

I'm currently working on designing a sidebar and I'm trying to figure out how to remove text decoration using the first-child selector. Here is a snippet of the HTML code I am working with: <aside> <nav> <div id="guid ...

What is the best way to position a logo at the center of a circle

My latest school project involves creating a contact page for my website, and I want to add social media icons inside circular containers. Below is the CSS code snippet I have used: .ul2{ display: flex; } .ul2 li{ position: relative; display: block ...

Ways to conceal CSS on the page when triggering a different element

I am trying to achieve the functionality of hiding the black arrow when clicking on the green arrow, all without using jQuery. Here is my fiddle: http://jsfiddle.net/t5Nf8/195/ html: <div class="arrow-down"></div> <div class="arrow-up"> ...

Is there a way to trigger this function with a button click event in Javascript, XSLT, XML, and HTML?

I need assistance with creating a webpage for my XML/XSL project that utilizes buttons to display country information when clicked. I initially achieved something similar using a dropdown list, but encountered issues when trying to implement buttons instea ...

Unable to extract all elements using simple HTML dom when parsing RSS feed

I've been attempting to extract various details like titles, descriptions, links, images, and dates from an RSS feed located at . However, for some reason, I am unable to retrieve the link tag and image source within the feed. The rest of the data ext ...

What is the best way to incorporate a highlighting bar below a link for emphasis?

How can I create a highlight effect above a link in the status bar, similar to what is seen on Fiddle sites? The highlight should remain above the active link and move to the link the mouse hovers over. Here is an example image of what I am trying to achie ...

The HTML markup is failing to display correctly

I'm struggling with the HTML and jQuery code I've written. Can anyone help me identify what's wrong with it? Below is the code snippet: <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml ...

Trouble selecting element using Selenium in Python

I had a script that was working fine, but suddenly it stopped working. Whenever I run the script, the item is not clicked and an error message appears. Traceback (most recent call last): File "/Users/6ko/Desktop/CodePython/katas/kata3.py", line ...

Issue encountered while attempting to transfer data via the $.ajax method

I created a poll form using radio buttons. To submit the form, I utilized $.ajax. However, when I tried using $("#polling").serialize() to gather the data, nothing was sent or requested... Could the issue be related to the radio buttons? $(function( ...

Pointer beneath navigation option

I have created a menu that includes an arrow underneath which slides under the selected item. This arrow is identified by the class "marker". Here is the HTML code: <div class="services-block"> <div id="services-carousel" class="carousel slide ...

Arrangement of elements using Bootstrap's order and column classes beneath

I'm having trouble with a bootstrap layout. Here is the layout I need to achieve on different screen sizes: On mobile, I want: Title Image Text And on desktop, I want: Image Title Text However, the title div always takes up the image he ...

What is the best way to ensure that only one div is toggled at a time while using the toggle class function?

$(document).ready(function(){ $("#items").children().click(function(){ $(this).toggleClass('clicked'); }); }); .clicked { background-color:red; } <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></s ...

Can the input field offer guidance on its own?

While browsing, I came across an HTML5 checkout form that grabbed my attention. You can view the source here I decided to make some changes to the form and discovered that entering an incorrect email address triggers helpful tips. Strangely, upon closer ...

Is it possible to apply a CSS transform without erasing the existing transform?

Looking for a solution: elem transform translateY(5px) scale(1.2) I want the element to move down an extra 5px on hover elem:hover transform translateY(5px) Is there a way to achieve this without knowing the previous state of the transform? Appr ...

JavaScript Time and Date Formatting

I'm pretty new to programming, especially in Javascript. Can someone help me simplify my code? I'm trying to create a dropdown for months and an input field for the year. Is there a more efficient way to make the month select box? Also, how can ...

Could someone please clarify a specific aspect of how floats work?

Could someone simplify this explanation for me? A float is positioned next to a line box if there is a vertical space that meets these conditions: (a) at or below the top of the line box, (b) at or above the bottom of the line box, (c) below the top margi ...

PHP - assign the student's name and grade to a corresponding skill category

(1) class https://i.sstatic.net/1kZS9.png (2) studentmark https://i.sstatic.net/fJexW.png (3) skill https://i.sstatic.net/lY3JX.png HTML code: <?php //CONNECT TO DATABASE //---(1)Fetch skillname--- $q = "SELEC ...

I have set a limit on the overall width of the elements, but I would like a particular element to

I set a global width, but I'm having trouble getting a specific element to exceed that limit. This element consists of text with a background image, and I want the image to extend beyond the width constraint. However, when I try to widen the element, ...

Checkbox in Bootstrap should be displayed before the submit button on smaller screens

I've been searching for a solution to this issue without any luck. In my setup, there are three input fields and a submit button displayed side by side on large screens, enclosed in <div class="col-sm"> to stack vertically on mobile devices. Ho ...