为什么div 100%宽度不能按预期工作

时间:2011-06-07 16:43:54

标签: html css html-table

我正在学习CSS并发现它并不总是那么直观(欢迎来到webdev,我猜)。 :)

为了创建一个简单的静态进度条,我使用下面的HTML文件:

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

我得到了这个:

Progress Bar

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

如何使用文本“填充”表格单元格而不强加特定的长度限制?

4 个答案:

答案 0 :(得分:3)

通过将文本div放在您的彩色div的内部(作为孩子),您告诉HTML您希望文本显示在彩色div中。所以内部div的宽度为100%意味着它的父div的宽度,你设置为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>

答案 1 :(得分:2)

这是你的html / css简介。谢谢我,当你收到我的账单;)。第一个...表格用于表格数据。不是布局第二......

#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;
}

这是html ...

<html>
    <head>
    </head>
    <body>
        <div id="wrapper">
            <div id="box_1">
                <p>stuff</p>
            </div>
        </div>
    </body>
</html>

希望这有助于您入门

答案 2 :(得分:0)

如果将width设置为%,则将采用其父元素的宽度。在您的情况下,div采用父元素的宽度,即td

答案 3 :(得分:0)

这是一个解决方案(我想?)

http://jsfiddle.net/tT2HR/

相关问题