IT

DIV가 전체 테이블 셀을 채우도록하십시오.

lottoking 2020. 6. 18. 07:32
반응형

DIV가 전체 테이블 셀을 채우도록하십시오.


나는 본 적이 이 질문을 하고 조금 인터넷 검색 ,하지만 아무것도 지금까지 근무하지 않았다. 나는 지금 2010 년이라고 생각합니다 (질문과 대답은 오래되었고 대답이 없습니다) CSS3가 있습니다! CSS를 사용하여 전체 표 셀의 너비와 높이를 채우기 위해 div를 얻는 방법이 있습니까?

셀의 너비 및 / 또는 높이가 미리 무엇인지 알 수 없으며 div의 너비 및 높이를 100 %로 설정하면 작동하지 않습니다.

또한 div가 필요한 이유는 셀 외부에 일부 요소를 절대적으로 배치 position: relative해야하고 tds 에는 적용되지 않기 때문에 래퍼 div가 필요하기 때문입니다.


다음 코드는 IE 8, IE 8의 IE 7 호환 모드 및 Chrome (다른 곳에서는 테스트되지 않음)에서 작동합니다.

<table style="width:100px"> <!-- Not actually necessary; just makes the example text shorter -->
   <tr><td>test</td><td>test</td></tr>
   <tr>
      <td style="padding:0;">
         <div style="height:100%; width:100%; background-color:#abc; position:relative;">
            <img style="left:90px; position:absolute;" src="../Content/Images/attachment.png"/>
            test of really long content that causes the height of the cell to increase dynamically
         </div>
      </td>
      <td>test</td>
   </tr>
</table>

당신은 해당 설정을 원래의 질문에 말했다 widthheight100%내가 그것을 무시 다른 규칙이 있음을 의심하게하는,하지만 일을하지 않았다. 너비 / 높이 규칙이 실제로 적용되는지 확인하기 위해 Chrome 또는 Firebug에서 계산 된 스타일을 확인 했습니까?

편집하다

내가 얼마나 어리석은가! div크기가 텍스트가 아닌 크기로 조정되었습니다 td. 를 만들어 Chrome에서이 문제를 해결할 수 div display:inline-block있지만 IE에서는 작동하지 않습니다. 까다로워지고 있습니다 ...


테이블 셀의 div height = 100 %는 테이블에 높이 속성이있는 경우에만 작동합니다.

<table border="1" style="height:300px; width: 100px;">
 <tr><td>cell1</td><td>cell2</td></tr>
 <tr>
   <td>
     <div style="height: 100%; width: 100%; background-color:pink;"></div>
   </td>
   <td>long text long text long text long text long text long text</td>
 </tr>
</table>

FireFox의 UPD 에서는 height=100%값을 상위 TD요소로 설정해야합니다


나는 높이를 가짜 높이설정 해야했다 .<tr><td>s

tr은 height: 1px(어쨌든 무시됩니다)

그런 다음 td를 설정하십시오 height: inherit

그런 다음 div를 height: 100%

이것은 IE edge와 Chrome에서 나를 위해 일했습니다.

<table style="width:200px;">
        <tr style="height: 1px;">
        <td style="height: inherit; border: 1px solid #000; width: 100px;">
              <div>
              Something big with multi lines and makes table bigger
              </div>
            </td>
            <td style="height: inherit; border: 1px solid #000; width: 100px;">
              <div style="background-color: red; height: 100%;">
              full-height div
              </div>
            </td>
        </tr>
    </table>


표 셀 안에 100 % div를 원하는 이유가 배경색을 전체 높이로 확장 할 수는 있지만 여전히 셀 사이에 간격을 둘 수 있다면 <td>배경색을 지정하고 CSS를 사용할 수 있습니다 셀 간 여백을 만드는 경계 간격 속성입니다.

그러나 100 % 높이 div가 정말로 필요하다면 다른 사람들이 언급했듯이 고정 높이를 지정 <table>하거나 Javascript를 사용해야합니다.


IE 7, 8 및 9를 포함한 다른 모든 브라우저 position:relative는 테이블 셀에서 올바르게 처리하고 Firefox 잘못 인식하므로 JavaScript shim을 사용하는 것이 가장 좋습니다. 하나의 실패한 브라우저에 대해 DOM을 변경할 필요가 없습니다. 사람들은 IE가 무언가 잘못되고 다른 모든 브라우저가 올바르게 얻을 때 항상 shim을 사용합니다.

다음은 모든 코드에 주석이 달린 스 니펫입니다. JavaScript, HTML 및 CSS는 필자의 예제에서 반응 형 웹 디자인 방식을 사용하지만 원하지 않는 경우에는 필요하지 않습니다. 반응 형은 브라우저 너비에 맞게 조정됩니다.

http://jsfiddle.net/mrbinky3000/MfWuV/33/

다음은 코드 자체이지만 컨텍스트가 없으면 의미가 없으므로 위의 jsfiddle URL을 방문하십시오. 전체 스 니펫에는 CSS와 Javascript 모두에 많은 주석이 있습니다.

$(function() {
    // FireFox Shim
    if ($.browser.mozilla) {
        $('#test').wrapInner('<div class="ffpad"></div>');
        function ffpad() {
            var $ffpad = $('.ffpad'),
                $parent = $('.ffpad').parent(),
                w, h;
            $ffpad.height(0);
            if ($parent.css('display') == 'table-cell') {               
                h = $parent.outerHeight();
                $ffpad.height(h);
            }
        }
        $(window).on('resize', function() {
            ffpad();
        });
        ffpad();
    }
});

나는을 사용하여 해결책을 제안한다 실험 셀의 내용 요소가 부모 셀을 세로로 채울 수있는 테이블 레이아웃 시뮬레이트 하는 Flexbox :

데모

.table{ display:flex; border:2px solid red; }
.table > *{ flex: 1; border:2px solid blue; position:relative; }
.fill{ background:lightgreen; height:100%; position:absolute; left:0; right:0; }

/* Reset */
*{ padding:0; margin:0; }
body{ padding:10px; }
<div class='table'>
  <aside><div class='fill'>Green should be 100% height</div></aside>
  <aside></aside>
  <aside>
    <p>Lorem ipsum dolor sit amet, consectetur adipiscing elit. Phasellus imperdiet, nulla et dictum interdum, nisi lorem egestas odio, vitae scelerisque enim ligula venenatis dolor. Maecenas nisl est, ultrices nec congue eget, auctor vitae massa. Fusce luctus vestibulum augue ut aliquet. Mauris ante ligula, facilisis sed ornare eu, lobortis in odio. Praesent convallis urna a lacus interdum ut hendrerit risus congue. Nunc sagittis dictum nisi, sed ullamcorper ipsum dignissim ac. In at libero sed nunc venenatis imperdiet sed ornare turpis. Donec vitae dui eget tellus gravida venenatis. Integer fringilla congue eros non fermentum. Sed dapibus pulvinar nibh tempor porta. Cras ac leo purus. Mauris quis diam velit. Lorem ipsum dolor sit amet, consectetur adipiscing elit. Phasellus imperdiet, nulla et dictum interdum, nisi lorem egestas odio, vitae scelerisque enim ligula venenatis dolor. Maecenas nisl est, ultrices nec congue eget, auctor vitae massa. Fusce luctus vestibulum augue ut aliquet. Mauris ante ligula, facilisis sed ornare eu, lobortis in odio. Praesent convallis urna a lacus interdum ut hendrerit risus conguet.</p>
  </aside>
</div>


며칠 동안 검색 한 후이 문제에 대한 가능한 수정 사항을 찾았습니다.

 <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1" />
<title>Documento sin título</title>
</head>

<body style="height:100%">
<!-- for Firefox and Chrome compatibility set height:100% in the containing TABLE, the TR parent and the TD itself. -->
<table width="400" border="1" cellspacing="0" cellpadding="0" style="height:100%;">  
  <tr>
    <td>whatever</td>
    <td>whatever</td>
    <td>whatever</td>
  </tr>
  <tr style="height:100%;">
    <td>whatever dynamic height<br /><br /><br />more content
</td>
    <td>whatever</td>

    <!-- display,background-color and radius properties in TD BELOW could be placed in an <!--[if IE]> commentary If desired.
    This way TD would remain as display:table-cell; in FF and Chrome and would keep working correctly.    
    If you don't place the properties in IE commentary it will still work in FF and Chorme with a TD display:block;

    The Trick for IE is setting the cell to display:block; Setting radius is only an example of whay you may want a DIV 100%height inside a Cell.
    -->

    <td style="height:100%; width:100%; display:block; background-color:#3C3;border-radius: 0px 0px 1em 0px;">

    <div style="width:100%;height:100%;background-color:#3C3;-webkit-border-radius: 0px 0px 0.6em 0px;border-radius: 0px 0px 0.6em 0px;">
    Content inside DIV TAG
    </div>
     </td>
  </tr>
</table>
</body>
</html>

스페인어 : El truco es establecer la Tabla, el TR y el TD 높이 : 100 %. FireFox 및 Chrome과 호환됩니다. Internet Explorer는 TD 코모 블록을 다운로드하여 사용할 수 있습니다. 익스플로러 시스템을 설치하십시오.

영어 설명 : 코드 주석 내


좋아, 아무도 이것을 언급하지 않아서이 트릭을 게시 할 것이라고 생각했습니다.

.tablecell {
    display:table-cell;
}
.tablecell div {
    width:100%;
    height:100%;
    overflow:auto;
}

overflow : cell 내 컨테이너 div의 auto 가 나를 위해 트릭을 수행합니다. 그것이 없으면 div는 전체 높이를 사용하지 않습니다.


So, because everyone is posting their solution and none was good for me, here is mine (tested on Chrome & Firefox).

table { height: 1px; }
tr { height: 100%; }
td { height: 100%; }
td > div { height: 100%; }

Fiddle: https://jsfiddle.net/nh6g5fzv/


I think that the best solution would be to use JavaScript.

But I'm not sure that you need to do this to solve your problem of positioning elements in the <td> outside of the cell. For that you could do something like this:

<div style="position:relative">
    <table>
        <tr>
            <td>
                <div style="position:absolute;bottom:-100px">hello world</div>
            </td>
        </tr>
    </table>
</div>

Not inline of course, but with classes and ids.


To make height:100% work for the inner div, you have to set a height for the parent td. For my particular case it worked using height:100%. This made the inner div height stretch, while the other elements of the table didn't allow the td to become too big. You can of course use other values than 100%

If you want to also make the table cell have a fixed height so that it does not get bigger based on content (to make the inner div scroll or hide overflow), that is when you have no choice but do some js tricks. The parent td will need to have the height specified in a non relative unit (not %). And you will most probably have no choice but to calculate that height using js. This would also need the table-layout:fixed style set for the table element


I encounter similar issues frequently and always just use table-layout: fixed; on the table element and height: 100%; on the inner div.


I ultimately found nothing that would work across all my browsers and all DocTypes / browser rendering modes, except for using jQuery. So here is what I came up with.
It even takes rowspan into account.

function InitDivHeights() {
    var spacing = 10; // <-- Tune this value to match your tr/td spacing and padding.
    var rows = $('#MyTable tr');
    var heights = [];
    for (var i = 0; i < rows.length; i++)
        heights[i] = $(rows[i]).height();
    for (var i = 0; i < rows.length; i++) {
        var row = $(rows[i]);
        var cells = $('td', row);
        for (var j = 0; j < cells.length; j++) {
            var cell = $(cells[j]);
            var rowspan = cell.attr('rowspan') || 1;
            var newHeight = 0;
            for (var k = 0; (k < rowspan && i + k < heights.length); k++)
                newHeight += heights[i + k];
            $('div', cell).height(newHeight - spacing);
        }
    }
}
$(document).ready(InitDivHeights);

Tested in IE11 (Edge mode), FF42, Chrome44+. Not tested with nested tables.


if <table> <tr> <td> <div> all have height: 100%; set, then the div will fill the dynamic cell height in all browsers.


If the table cell is the size that you want, just add this css class and assign it to your div:

.block {
   height: -webkit-calc(100vh);
   height: -moz-calc(100vh);
   height: calc(100vh);
   width: 100%;
}

If you want the table cell to fill up the parent too, assign the class to table cell too. I hope it helps.


you can do it like that:

<td>
  <div style="width: 100%; position: relative; float: left;">inner div</div>
</td>

a bit late to the party but here's my solution:

<td style="padding: 0; position: relative;">
   <div style="width: 100%; height: 100%; position: absolute; overflow: auto;">
     AaaaaaaaaaaaaaaaaaBBBBBBBbbbbbbbCCCCCCCCCccccc<br>
     DDDDDDDddddEEEEEEEEdddfffffffffgggggggggggggggggggg
   </div>
</td>

I'm not sure what you want to do but you might try this one:

<td width="661" valign="top"><div>Content for New Div Tag Goes Here</div></td>


The following should work. You have to set a height to the parent cell. https://jsfiddle.net/nrvd3vgd/

<table style="width:200px; border: 1px solid #000;">
    <tr>
        <td style="height:100px;"></td>
    </tr>
    <tr>
        <td style="height:200px;">
            <div style="height:100%; background: #f00;"></div>
        </td>
    </tr>
</table>

Try this:

<td style="position:relative;">
    <div style="position:absolute;top:0;bottom:0;width:100%;"></div>
</td>

Try putting display:table block inside a cell


I does not watch here an old CSS-trick for <div> inside <td>. Hence I remind: simple set some minimal value for width, but what-you-need for min-width. For example:

<div style="width: 3px; min-width: 99%;">

The td's width, in that case, is up to you.


This is my Solution for extend 100% height and 100% width in a html <td>

if you delete the first line in your code you can fix it ...

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
 "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

because this doctype does not permit in some files to use the 100% percent inside of <td>, but if you delete this line, the body fails expanding the background to 100% height and 100% width, so I found this DOCTYPE that solves the problem

<!DOCTYPE html PUBLIC "-//IETF//DTD HTML 2.0//EN">

this DOCTYPE let you extends the background in your body as 100% height and 100% width, and let you take all the 100% height and 100% width into the <td>

참고URL : https://stackoverflow.com/questions/3215553/make-a-div-fill-an-entire-table-cell

반응형