Zergatul
Zergatul

Reputation: 2010

How to fix parent element width to one of its child?

Can I fix width of div.main to be the same as table.tbl2? In the example below, I need inline4 to be on the second line, and width of div.main equal to width of table.tbl2.

.container {
  text-align: center;
}

.main {
  display: inline-block;
  border: 1px solid black;
}

.tbl1 {
  width: 100%;
}

.tbl2 {
  border: 1px solid red;
  border-collapse: collapse;
}

.tbl2 td {
  border: 1px solid red;
}

.inline-div {
  display: inline-block;
}
<div class="container">
  <div class="main">

    <table class="tbl1">
      <tr>
        <td>text text text text</td>
      </tr>
    </table>

    <table class="tbl2">
      <tr>
        <td>text 1</td>
        <td>text 2</td>
        <td>text 3</td>
        <td>text 4</td>
      </tr>
    </table>

    <div class="inline-div">inline1</div>
    <div class="inline-div">inline2</div>
    <div class="inline-div">inline3</div>
    <div class="inline-div">inline4</div>

  </div>
</div>

Upvotes: 0

Views: 47

Answers (1)

Temani Afif
Temani Afif

Reputation: 272589

An idea is to make the elements out of the flow so they won't affect the width. This is not a generic solution as you need to adjust few things depending on each situation.

.container {
  text-align: center;
}

.main {
  display: inline-block;
  border: 1px solid black;
  border-bottom:0;
  position:relative;
}

.tbl1 {
  width: 100%;
}

.tbl2 {
  border: 1px solid red;
  border-collapse: collapse;
}

.tbl2 td {
  border: 1px solid red;
}
.bottom {
  position:absolute;
  right:-1px;
  left:-1px;
  top:100%;
  border:1px solid black;
  border-top:none;
}

.inline-div {
  display: inline-block;
}
<div class="container">
  <div class="main">

    <table class="tbl1">
      <tr>
        <td>text text text text</td>
      </tr>
    </table>

    <table class="tbl2">
      <tr>
        <td>text 1</td>
        <td>text 2</td>
        <td>text 3</td>
        <td>text 4</td>
      </tr>
    </table>
    <div class="bottom">
    <div class="inline-div">inline1</div>
    <div class="inline-div">inline2</div>
    <div class="inline-div">inline3</div>
    <div class="inline-div">inline4</div>
    </div>
  </div>
</div>

Upvotes: 1

Related Questions