Why does CSS respect height:auto for relative positioned parent elements but not width:auto?

Although CSS position properties may seem simple at first, when building a layout, tons of weird edge cases can come out of nowhere.

One thing that I always overlooked was using height: auto or width: auto. To gain a better understanding, I stumbled upon the code below and now I'm hoping someone can explain why this phenomenon occurs.

I'm puzzled because when position: absolute is used and both height and width are set to auto on the parent element, the parent ends up being 50px x 50px.

However, this behavior does not occur when the parent is relatively positioned. In such case, even though height: auto works fine, setting width: auto does not cause the parent to match the width of its child as expected. Instead, with position: relative, the element extends along the entire line.

body {
  margin: 0;
  padding: 0;
}

.a {
  /*
    Why is 'width:auto' not respected while 'height:auto' takes the height of the child??

    If 'position' were set to 'absolute', then both 'height' and 'width'
    would take on the dimensions of the child element
  */
  position: relative;
  background: #ff9999;
  top: 10px;
  height: auto;
  width: auto;
}

.b {
  position: relative;
  background: blue;
  top: 10px;
  height: 50px;
  width: 50px;
}
<div class="a">
  <div class="b"></div>
</div>

Answer №1

Understanding the width of an element is not just about its position, but also how it is displayed. For a comprehensive guide on how each element's width is calculated, check out this resource.

There are various categories to consider, especially when dealing with elements that have a position: relative. In these cases, factors like being a block level element, and following specific rules play a significant role in determining the width.

'margin-left' + 'border-left-width' + 'padding-left' + 'width' + 'padding-right' + 'border-right-width' + 'margin-right' = width of containing block

On the other hand, elements with position: absolute adhere to different guidelines, where the width is calculated based on fitting to the content.

.. then the width is shrink-to-fit

While there are numerous cases to consider, a quick look at the provided link will give you a solid understanding of how element width and height calculations work.

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

Is it possible to examine elements within Outlook?

Creating HTML emails can be quite the challenge, especially when trying to make them compatible with Outlook. Is there a method to inspect elements in Outlook similar to how we do on a browser's console? ...

Use jQuery to display the user input value in real-time

I am in the process of developing a dynamic calculation program to sharpen my jQuery skills, but unfortunately, I'm facing some challenges. I have managed to store values in variables as shown in the code snippet below. <form> Table of: ...

Creating a customized icon scheduling feature with CSS

Creating an icon using CSS that looks like the one below seems to be quite challenging. I attempted to achieve it with this approach, but the result was not satisfactory. https://i.stack.imgur.com/5W7Hj.png .schedule { height: 10px; width ...

Show the text from the chosen option using jQuery with a button

Hey everyone, I have a question regarding a coding issue I'm facing. In this problem, I am unable to display the text from the selected option when I click the order button. The desired result is to show the selected option that I choose and display i ...

Styling CSS: Create circular images with dynamic text positioning or resizing on screens larger than 768px

I'm struggling to figure out how to create a circular profile picture on a background image that remains responsive and maintains its position across different screen sizes. Currently, I've been using fixed margin values to adjust the position, ...

The device-width value in the viewport width setting is causing issues

My angular app desperately needs a mobile responsive design as it currently looks dreadful on mobile devices. I've tried adding <meta name="viewport" content="width=device-width, height=device-height, initial-scale=1.0, user-scalable=yes">, but ...

Exploring the theme color options in Angular Material

Despite extensive searching on SO and GitHub, I am seeking clarification: Is it impossible to access a theme color (or any other theme feature) in order to set a mat-card color? There is no way to retrieve a variable in scss. You cannot assign a class to ...

What is causing Firefox to display an additional line in this section?

After much effort, I've been attempting to eliminate the extra spacing on this page in Firefox: Do you see the menu? If you compare it to Chrome, you'll notice that the menu is positioned too low beneath the background, giving the layout a broke ...

Move the button text back to its original position with animation

I have a button with text that shifts to the right by 15px when hovered over. However, when the cursor is removed, the text immediately snaps back instead of smoothly transitioning back to its original position. I tried setting the ease-in-out property but ...

Issue encountered: Compilation error occurred following the update from Angular 11 to Angular 15, stemming from the module build failure within the sass-loader directory

I recently attempted to update angular from version 11 to 15, but encountered an error as shown in the screenshot below ./src/assets/styles.scss - Error: Module build failed (from ./node_modules/sass-loader/dist/cjs.js): SassError: expected "(". ...

Enhancing text display and spacing in Safari versions 5 to 6, as well as Chrome

After creating an introductory animation using jquery, I noticed that it displays correctly on my machine in Firefox, Chrome, and Safari. However, when viewing it on the client's devices, the animation is not working properly. The client provided a s ...

Can I position two div elements next to each other, with one div partially offscreen, without utilizing display none or setting its width to zero?

Is it possible to position one div outside of the screen width while setting two divs side by side? I am looking to insert DIV2 above DIV1 with animation without adjusting its width or display. The goal is for DIV2 to enter the screen from the side alread ...

Tips for increasing the size of a textarea

I'm attempting to extend a textarea by adjusting the margin-top property, but it doesn't seem to be working as intended. Here is the code snippet in question: #sqlcontainerLoggedInPage2 { margin-top: 60px; } <div class="container-fluid" i ...

Addressing responsiveness problems with Bootstrap navigation bar

Seeking assistance with setting up the fundamental bootstrap grid system. Despite my efforts, I am unable to make it work. Could someone guide me in creating the basic structure for the Navbar above? Specifically, focusing on using columns and rows with p ...

Utilize Angular2's input type number without the option for decimal values

Is there a way to prevent decimals from being entered in number inputs for Angular 2? Instead of using patterns or constraints that only invalidate the field but still allow typing, what is the proper approach? Would manually checking keystrokes with the ...

Securing Your WordPress Custom Form with Captcha

I have a unique form on my WordPress website that tracks IP addresses, checks referer pages, and validates email addresses. Despite these measures, I am still receiving spam subscriptions. I have tried implementing both Bestwebsoft CAPTCHA and really sim ...

Enhancing User Experience with CSS Transitions for Faster Page Loading

Recently, I stumbled upon a captivating website that has left me in awe - . The mesmerizing aspect of this site lies in the seamless and fluid animations that gracefully transition when navigating between pages. I find myself yearning to understand the int ...

Perform an SQL function to select and update data

I need to run this code, but I'm missing one key variable that I can't seem to locate. Here's my current code snippet: SELECT CODE = 'P1R2G1' and CATEGORY = '20M' IF RANK op1 = '1' THEN UPDATE tourneyeventga ...

Delete the option to alter button in the Jasny file input tool

I recently incorporated the Jasny Fileinput Widget into my existing form. However, I noticed that when I select a new file, it displays two buttons: Change and Remove. In this case, I believe the Change button is unnecessary and would like to remove it com ...

Understanding Arrays in Angular JSIn this article, we

I am new to working with Angular JS. Currently, I am populating an array and attempting to showcase its contents on the HTML page using ng-repeat. $scope.groupedMedia = []; // Elements are being added through a for loop. $scope.groupedMedia[year].push(r ...