Why is it that using div with a 100% width doesn't behave as one would anticipate?

Learning CSS has been an interesting journey so far. It's not always as intuitive as one might think, especially in web development. :)

I recently attempted to create a simple, static progress bar using the following HTML file:

<html>
  <head></head>
  <body>
    <table border='1' cellspacing='0'>
      <tr>
        <td>Sample Cell</td>
        <td>
          <!-- This is meant to be a progress bar -->
          <div style="background-color: #0a0; width: 20%;">
            <div style="text-align: center; width: 300px;">
              Text Here!
            </div>
          </div>
        </td>
      </tr>
    </table>
  </body>
</html>

The result looks promising, however, I noticed that the width of the second column is fixed. When I tried changing width: 300px to width: 100%, the text ended up inside the green box rather than filling the entire table cell.

I'm now wondering how I can make the text fill the whole table cell without specifying a specific length restriction. Any suggestions?

Answer №1

When you nest your text div inside a colored div, you are indicating to HTML that the text should be contained within the colored div. This means that setting a width of 100% on the inner div will make it match the width of its parent div, which in this case is set to 20%.

UPDATE: added code *UPDATE: revised code*

<html>
<head>
    <style>
        #bar{
            width: 100%;
            position: relative;
        }

        #progress{
            background-color: #0a0;
            width: 20%;
            position: absolute;
            z-index: 0;
        }

        #progress_text{
            text-align: center;
            width: 100%;
            position: relative;
            z-index:1;
        }
        .progress_cell{

        }

    </style>
  </head>
  <body>
    <table border='1' cellspacing='0'>
      <tr>
        <td>Sample Cell</td>
        <td class="progress_cell">
          <div id="bar">
             <!-- This is meant to be a progress bar -->
             <div id="progress">
               &nbsp;
             </div>
             <div id="progress_text">
                  Text Here! Text Here! However, it might be too long and cause an overflow...
             </div>
          </div>
        </td>
      </tr>
    </table>
  </body>
</html>

Answer №2

Introducing you to the basics of HTML/CSS. Don't forget to thank me later when you see my bill ;). Remember, tables should be used for tabular data, not layout.

#wrapper {
    position:absolute;
    top:10px;
    left:50%;
    width:900px;
    height:500px;
    margin:0px auto 0px -450px;
    padding:0px;
    background-color:#369;
}

#box_1 {
    width:100%;
    height:100px;
    margin:0px auto;
    padding:0px;
    background-color:red;
}

And here's the sample HTML code...

<html>
    <head>
    </head>
    <body>
        <div id="wrapper">
            <div id="box_1">
                <p>Content goes here</p>
            </div>
        </div>
    </body>
</html>

I hope this information helps you kickstart your journey into web development.

Answer №3

When you specify a width in percentage, the element will take up that percentage of its parent element's width. In this scenario, the div is inheriting the width of its parent element, which is the td.

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

JSFiddle showcasing the Bootstrap grid system

I'm having trouble implementing bootstrap's grid system on jsfiddle. Check it out on jsfiddle I've tried using the example from the bootstrap documentation: <div class="row"> <div class="col-md-1">.col-md-1</div> ...

Issues with the functionality of Bootstrap

Upon loading the page, I am encountering an issue with a collapse on the 'main' id. It fails to collapse initially and only functions correctly after being clicked. I have not utilized 'collapse in', so I am unsure why this behavior per ...

Why is Python BeautifulSoup's findAll function not returning all the elements in the web page

I am attempting to retrieve information from the following URL . Displayed below is the code I have developed. import requests from bs4 import BeautifulSoup url_str = 'https://99airdrops.com/page/1/' page = requests.get(url_str, headers={&apo ...

The functionality of Jquery AJAX is operational, however, the message being displayed appears to

Inside the file changename.php, there is a DIV element: <div id="resultDiv"></div> Within the same file, PHP code can be found: <?php include_once ('connect.php'); if(isset($_POST['name'])) { $postedname = $_POST[&ap ...

Troubleshooting issue with AngularJS ng-repeat not functioning properly when using Object key value filter with ng-model

Is there a way to have an object with an ID as a key value pair? For example: friends = { 1:{name:'John', age:25, gender:'boy'}, 2:{name:'Jessie', age:30, gender:'girl'}, 3:{name:'Johanna', ag ...

Angular does not support fetching JSON files

update: The code has been modified to include the latest suggestions provided by you all. I've got this data.json file: [{ "codigo": 21420, "desc": "itv orion 20 a", "prod_24_h_kg": 22 }, { "codigo": 21421, "desc": "itv orion 20 w", "prod_24_h_kg": ...

Step-by-step guide on incorporating edit, update, and discard functionalities within an Angular Material table component (mat-table)

I am currently working on implementing edit, update, and discard functions in an angular material table. While I have been able to successfully edit and update the table row wise, I am struggling with how to discard table rows. If you would like to see wh ...

Matching Regex Patterns for Parents and Children

Regex has always been a struggle for me, so I could really use some guidance. I'm attempting to create opening and closing 'tags' with the same regex permitted inside these tags. For example, a tag might look like: <: tagname("[captur ...

Trouble with meta og:image on my SSL-secured WordPress site

Having some trouble adding meta properties to my WordPress website that is SSL certified. When I share the link on Skype and WhatsApp, the og:image is not working. I've tried multiple plugins and even directly added HTML code to my WordPress theme hea ...

Tips for achieving a background animation similar to the one shown on this page

Check out this link: danielcoding.me/resume/#contact I am interested in this animation: screenshot I tried inspecting element on the page, but couldn't find any background images. How can I create this animation? Is it achieved through JavaScript or ...

Using class binding for both ternary and non-ternary attributes

Suppose we have a tag that utilizes a ternary operator to apply alignment: <td :class="alignment ? ('u-' + alignment) : null" > This functions as intended since the pre-defined alignment classes are in place, now if we want to ...

Ensuring even distribution of three divs within a container

Imagine a container that is 1200px wide, with three divs inside. Each div is only 292px wide. The first div should align with the left margin, the third div with the right margin, and the second div should sit right in the middle of them. Adding to the c ...

Highlight the parent name in the menu when I am on the corresponding child page

Here is a snippet of a recursive function: function recursive($arrays, $out) { if (is_array($arrays)){ //$out .= "<ul>"; foreach($arrays as $parent => $data) { //if parent is empty if ($parent === '') { ...

When a <dl> element is nested within an <ol>, it will be rendered as a list format

I'm facing an issue with my CSS that affects how different browsers render definition lists embedded within ordered lists. In IE10, the list displays as expected - a bulleted list inside the ordered list without affecting the numbering. However, Firef ...

Implement an innovative solution to automatically close the navbar component in tailwindcss on

I've been attempting to create a unique tailwind navbar component for React, but I've encountered issues when trying to make it close on scroll for mobile view. I found the initial code on this website. After that, I tried implementing the code ...

Send your information without having to navigate away from the current

This is my form <form id="reservationForm" action="sendmail.php" method="post"> ... . . . . <input type="image" src="images/res-button.png" alt="Submit" class="submit" width="251" height="51px"> Here is my javascript $("#reservationForm").su ...

Creating a Canvas Viewport Tailored for Multiplayer Gaming

Lately, I've been playing around with the HTML5 Canvas while working on an io game. However, I've hit a roadblock when it comes to handling the viewport. Setting up the viewport itself isn't too complicated, but accurately displaying other p ...

Hovering over overlapping spans without moving them

For the text formatting, I attempted to use the following code: <style> #items { width:400px; padding: 10px; } .esp { float: left; background-color: yellow; position:relative; z-index:0; } .le { float: left; position:rela ...

Tips for resizing the MUI-card on a smaller screen

Is there a way to adjust the width of the card on small screen sizes? It appears too small. You can view my recreation on codesandbox here: https://codesandbox.io/s/nameless-darkness-d8tsq9?file=/demo.js The width seems inadequate for this particular scr ...

Ways to adjust the dimensions of a textarea based on character count

When attempting to utilize the cols and rows attributes of the <textarea> element in order to set the width and height in characters, I have encountered issues even without implementing CSS. Take a look at this example: link I have configured a 5x5 ...