basZero
basZero

Reputation: 4284

Table is using more than 100% width of its parent element, how can this be fixed by CSS only?

I have a root div using 100% width and I want all children not to overlap (overflow:hidden) and also not to use more width than this 100%.

This works fine when I work with inner <div>s, but if <table>s are used, the table gets too wide, using more than the parent 100% div.

How can this be fixed while keeping the table?

Here is the JSFiddle.

Screenshot:
enter image description here

Upvotes: 4

Views: 7246

Answers (3)

Pete
Pete

Reputation: 58462

if you add the following styles, it should fix your problem:

#wrapper table {
  table-layout:fixed;
}
#wrapper table td {
  overflow:auto; /* can be hidden if you want to hide it */
}

Updated code:

#wrapper {
  width: 100%;
  box-sizing: border-box;
  padding: 20px;
}
#item {
  padding: 10px;
  border-style: solid;
  border-color: #ff0000;
  border-width: 1px;
  overflow: hidden;
}
#wrapper table {
  width: 100%;
  border-style: solid;
  border-color: #ff0000;
  border-width: 1px;
  table-layout: fixed;
}
#wrapper table td {
  overflow: auto;
}
#wrapper table td:nth-child(1) {
  width: 10%;
}
#wrapper table td:nth-child(2) {
  width: 90%;
}
<div id="wrapper">
  <div id="item">
    This is a normal text box where the width gets preserved correctly.
  </div>
  <div id="item">
    this div contains a very long word, e.g. https://upload.wikimedia.org/wikipedia/commons/c/ca/Simca_1300_Serie_1_rear_20110114.jpg and the width does correctly not use more than 100% of the parnet's width.
  </div>
  <table>
    <tr>
      <td>Col1</td>
      <td>Col2 mit viel Text https://upload.wikimedia.org/wikipedia/commons/c/ca/Simca_1300_Serie_1_rear_20110114.jpg the width gets too wide! How can I make this DIV to be not wider than the parent?</td>
    </tr>
  </table>
</div>

Upvotes: 5

Sonny Prince
Sonny Prince

Reputation: 1152

you could add word-break: break-all; to your td

Upvotes: 0

Krish
Krish

Reputation: 1894

You should give word-break: break-word; for td text , because the text is a large length, or you can give td text as word-break: break-all; for breaking the text.

updated css code

#wrapper table td{
  word-break: break-word;
}

demo fiddle: https://jsfiddle.net/nikhilvkd/kLt1mec8/3/

Upvotes: 7

Related Questions