简体   繁体   中英

Make an element's width depend on its grandparent's dynamic width--while having a fixed width parent

Pew, sounds complicated, huh? I try to describe it as good as I can. So basically, we have three elements: A div whose width is auto, a table whose width is exactly 500 and a span whose width should also be auto, but is completely dependant on the table's cell width.

Let me show it to you:

<div>
  <table>
    <tr>
      <td><span>Some random content</span></td>
      <td><span>Some random content</span></td>
    </tr>
    <tr>
      <td><span>Some random content</span></td>
      <td><span>Some random content</span></td>
    </tr>
  </table>
</div>

Here's the CSS; with borders for enhanced clarity:

table, tr, td {
    border: 1px solid black;
}

table {
    width: 500px;
}

span {
    border: 1px dotted red;
    display: block;
    word-wrap: break-word;
}

div {
    border: 1px dotted green;
}

Rendered, it looks like this:

在此处输入图片说明

Perfectly fine. Noticed the green dotted border? That's the div: as wide as the browser window. However, if I resize the whole thing, it looks like this:

在此处输入图片说明

Look at the green border now: The div properly resized itself as expected. The red dotted border (the span), is still as wide as the table, though. Is it possible that it resizes itself according to the div, rather than to the table, so you can still read the entire text?

Thanks in advance.

try percentage for table's width, to make it fluid, something like width: 26% if you screen size is 1920px. 500/1920 * 100. So he's gonna adapt to screen size, but if you want fixed width at full screen, and smaller after you must use some media query.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM