为什么div 100%宽度无法按预期工作 [英] Why div 100% width doesn't work as expected

查看:67
本文介绍了为什么div 100%宽度无法按预期工作的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在学习CSS,发现它并不总是那么直观(我想欢迎使用webdev). :)

I'm learning CSS and finding that it's not always so intuitive (welcome to webdev, I guess). :)

为了制作一个简单的静态进度栏,我使用下面的HTML文件:

In an attempt to make a simple, static progress bar, I use the HTML file below:

<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>

我明白了:

这很好,除了第二列的宽度是固定的.但是,如果我继续将width: 300px更改为width: 100%,则文本将进入绿色框,而不是整个表格单元格.

which is good, except for the fact that the width of the second column is fixed. But if I go ahead and change width: 300px to width: 100%, the text instead goes into the green box, rather than the whole table cell.

如何在不施加特定长度限制的情况下用文本填充"表格单元格?

How can I "fill" the table cell with the text, without imposing a specific length restriction?

推荐答案

通过将文本div放置在彩色div中(作为彩色div的子代),您告诉HTML希望文本出现在彩色div中.因此,内部div上100%的宽度意味着其父div的宽度是多少(您已将其设置为20%).

By placing your text div inside (as a child of) your colored div, you're telling HTML that you want the text to appear inside the colored div. So a width of 100% on the inner div means whatever the width of its parent div is, which you have set to 20%.

添加了代码 * 更新的代码 *

<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! But it's really long, and it's going to overflow ...
             </div>
          </div>
        </td>
      </tr>
    </table>
  </body>
</html>

这篇关于为什么div 100%宽度无法按预期工作的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆