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

The output of VueJs hooks shows a blank refs object first, followed by the referenced elements

Below is the HTML VueJS code sample that I am working with: <div v-for="site in topSites" ref="ts"><a :href="site.url"> ... </div> Update: Here is the full div code: <div v-for="site in topSites& ...

What steps should I take to correct the color selection of a button that has been pressed down

Here is the code snippet that I am currently working with: HTTP: <label class="instructions" for="hidden_x"> Insert X: </label> <button type="button" class="button" name="button_x" value="1" id="x_1" onclick="document.getElementById(' ...

Select a specific date range from a form and export CSV file containing MySQL data within that range

I have successfully implemented a database CSV export functionality, but now I am looking to allow the user to specify a date range for the export process. Below is the HTML section that handles the date selection (date format: mm/dd/yyyy): <form act ...

The issue of MUI components overlapping arises during window resizing

I am currently working on a chat component that includes both the chat display and message input fields. function Chat() { const chatBoxStyles = { bgcolor: "red", height: "70vh", mt: "1rem" }; const messageIn ...

Once the PHP page loads, it becomes challenging for me to dynamically change values in JavaScript

Within my code snippet below, I am aiming to modify the initial value using a slider. The slider appears to be functioning correctly; however, it is not updating the values of timeout as indicated beneath the line $('ul.<?php echo $this->session ...

What is the best way to assign string values from an array in data() to the src attribute of an image element?

I've been working on a feature where the <div.box> element appears based on the user's input through a form. In this project, I'm using vue3 and v-for to iterate over an array 'images' that contains URL strings linking to ima ...

Extension Overlay for Chrome

I'm currently working on developing a Chrome extension, but I'm encountering some confusion along the way. Despite researching online, I keep receiving conflicting advice and haven't been able to successfully implement any solutions. That&ap ...

PHP mail function not working properly when ajax is used

On my MAC, I am attempting to utilize php mail with ajax implementation. I have simplified my code to just strings: In my .js file : function sendMail() { $('#sending').show(); $.ajax({ type:'POST', ...

Getting the full referrer URL can be achieved by using various methods depending

I am currently working with ASP.Net. My goal is to retrieve the complete referrer URL when visitors arrive at my website from: https://www.google.co.il/webhp?sourceid=chrome-instant&rlz=1C1CHEU_iwIL457IL457&ion=1&espv=2&ie=UTF-8#q=%D7%90 ...

The functionality of the Bootstrap navbar-fixed-top seems to be malfunctioning

I am currently working on creating a page layout with a fixed navigation bar positioned at the top. I am aiming for a design similar to the one showcased here. Upon examining the example linked above, it appears that the content of the page begins below t ...

Adjust the anchor tag content when a div is clicked

I have a list where each item is assigned a unique ID. I have written the HTML structure for a single item as follows: The structure looks like this: <div id='33496'> <div class='event_content'>..... <div>. ...

Tips for horizontally arranging a list with a flexible number of columns

I am attempting to create a horizontal list with 3 columns that automatically moves to a new line when the columns are filled. I have been trying to implement this using PHP but haven't had any success. If anyone could provide some guidance on how to ...

Discovering the potential of HTML5 Canvas matrix transformations

Throughout various Html5 resources, authors frequently discuss: transform(1,0,0,1,0,0) being equivalent to transform(0,1,1,0,0,0). I find this confusing. From my perspective, that implies newX = oldX/newY = oldY is the same as newX = oldY/newY = oldX. ...

The controller is failing to effectively showcase the ng-show functionality

My webpage consists of three elements: a search bar, a search result area, and a form. The use case scenario involves showing the search bar and form div by default, while hiding the search result div. When I enter keywords into the search bar, client data ...

Make Jekyll process HTML files even without front matter by using the Knitr tool to add front matter to the HTML files

I am currently utilizing RMarkdown in combination with knitr to produce various HTML documents. After uploading these documents to GitHub, Jekyll is utilized for rendering the files onto GitHub pages. My objective is straightforward: I want the index.html ...

Having trouble accessing the iframe element in an Angular controller through a directive

My webpage contains an iframe with a frequently changing ng-src attribute. I need to execute a function in my controller each time the iframe's src changes, but only after the iframe is fully loaded. Additionally, I require the iframe DOM element to b ...

The combination of Spring Boot and Angular's routeProvider is a powerful

I have been working on a project using Spring Boot, REST, and AngularJS. While I successfully implemented the back end with REST, this is my first time using AngularJS. Despite watching numerous tutorials and following them step by step, I am still facing ...

Feeling lost when it comes to forms and hitting that submit button?

Below is a sample form structure: <html> <head> <title>My Page</title> </head> <body> <form name="myform" action="http://www.abcdefg.com/my.cgi" method="POST"> <div align="center"> <br><br; <br& ...

Struggling to implement a Datepicker in the date column of a table created using HTML and JavaScript

I am encountering an issue while creating a table in html and javascript. I am unable to use a Datepicker in the date column when inserting a new row, even though it works fine when using in normal html code. Below is the javascript function: //Script fo ...

I am looking to integrate my information into the user interface using Angular

import { Component, ViewEncapsulation } from '@angular/core'; import { Router } from '@angular/router'; import { Batch } from '../../../config/batchnew/batch.model'; import { BatchService } from '../../../config/batchnew ...