css display:table not displaying the border

2019-03-09 14:49发布

<html>
    <style type="text/css">
        .table   { display: table;}
        .tablerow  { display: table-row; border:1px solid black;}
        .tablecell { display: table-cell; }
    </style>
    <div class="table">
        <div class="tablerow">
            <div class="tablecell">Hello</div>
            <div class="tablecell">world</div>
        </div>
        <div class="tablerow">
            <div class="tablecell">foo</div>
            <div class="tablecell">bar</div>
        </div>
    </div>
</html>

According to my understanding,a black border should be drawn on each of the rows which i've specified via tablerow class.But the border doesnt come up.

And i wanted to change the height of a row.If i specify it with 'px' -- it work.But,if i give it with a % -- wont work.I tried the following

.tablerow  { 
    display: table-row;
    border:1px solid black;
    position: relative; //not affecting anything and the border disappears!! 
    //position: absolute; // if this is set,the rows overlaps and the border works
    height: 40%; // works only if specified in px and not in %
}

Something is going wrong somewhere, but I am not able to understand where. Please help!

3条回答
小情绪 Triste *
2楼-- · 2019-03-09 15:32

Table rows can't have a border attribute. You can get a border around each row by giving all cells a top and bottom border, and adding a class for the left-most and right-most cells with a left and right border respectively.

JS fiddle link

edit: I forgot about border-collapse:collapse. That will work too.

查看更多
男人必须洒脱
3楼-- · 2019-03-09 15:37

You need to add the border to the tablecell class.

Also, to make it look nice, you will need to add border-collapse:collapse; to the table class.

Example: http://jsfiddle.net/jasongennaro/4bvc2/

EDIT

As per the comment

i'm applying a border to a div,it should get displayed right ?

Yes, but once you set it to display as a table that is how it will act... as a table, so you will then need to follow the css rules for displaying tables.

If you need to set the border only on the rows, use border-top and border-bottom and then set specific classes for the leftmost and rightmost cells.

查看更多
姐就是有狂的资本
4楼-- · 2019-03-09 15:44

You need to add border-collapse: collapse; to the .table class for it to work like this:

<html>
<style type="text/css">
    .table   { display: table; border-collapse: collapse;}
    .tablerow  { display: table-row; border: 1px solid #000;}
    .tablecell { display: table-cell; }
</style>
<div class="table">
    <div class="tablerow">
        <div class="tablecell">Hello</div>
        <div class="tablecell">world</div>
    </div>
    <div class="tablerow">
        <div class="tablecell">foo</div>
        <div class="tablecell">bar</div>
    </div>
</div>
</html>
查看更多
登录 后发表回答