
ในการทำเว็บไซต์ให้เป็น responsive นั้นอีกหนึ่งปัญหาที่ค่อนข้างลำบากคือการทำให้ table grid ที่มีข้อมูลค่อนข้างมากหลายคอลั่มน์ยาวเกินหน้าจอสำหรับโมบายหรือหน้าจอเล็กก็เลยลองหาวิธีไปเจอมาหนึ่งวิธีที่ค่อนข้างดี โดยใช้ css เท่านั้น
เรามาเริ่มจากตัวอย่างกันครับ
การแสดงผลตัวอย่างบน Desktop
การแสดงผลตัวอย่างบน Mobile
ทีนี้เราจะมาดู css code ที่สำคัญกันครับ
.tableresponsive{
margin:15px auto;
}
/* ในส่วนนี้จะเป็นการกำหนด table ในรูปแบบของ desktop */
.tabledata{
width:100%;
padding:0;
margin:0;
font-family: Verdana, Geneva, Tahoma, sans-serif;
font-size: 13px;
color:#9c9b99;
}
.tabledata thead tr th{
background:#0eac38;
color:#fff;
text-align: center;
padding:7px 5px;
}
.tabledata tbody tr td{
padding:7px 5px;
text-align: center;
cursor:pointer;
border-bottom: 1px solid #d6d6d6;
}
.tabledataa a{
display:inline-block;
border: 1px solid #189e3d;
padding:5px;
color:#a09a9a;
background:#fff;
-webkit-transition: all .25s ease-out;
-moz-transition: all .25s ease-out;
-ms-transition: all .25s ease-out;
-o-transition: all .25s ease-out;
transition: all .25s ease-out;
}
.tabledataa a:hover{
background:#189e3d;
color:#fff;
}
.tabledataa tbody tr:hover td{
background:#7f7f7f;
color:#fff;
}
/* ในส่วนนี้จะเป็นการกำหนด table ในรูปแบบของ Moblie media query ผมเซ็ตไว้ที่ 430 คือหน้าจอต่ำกว่านี้จะแสดงผลครับ */
@media only screen and (max-width: 430px) {
.tableresponsive table,
.tableresponsive thead,
.tableresponsive tbody,
.tableresponsive th,
.tableresponsive td,
.tableresponsive tr
{
display:block ; /* เปลี่ยน display ของ table ทั้งหมดไม่ว่าเป็น th tr td thead tbody */
}
.tableresponsive thead tr {
position: absolute ;
top: -9999px;
left: -9999px;
}
.tableresponsive tr { border: 1px solid #ccc; }
.tableresponsive td { /* ในส่วนี้ปรับขนาด td */
border: none;
border-bottom: 1px solid #eee;
position: relative;
padding-left: 45% !important;
white-space: normal;
text-align:left;
}
.tableresponsive td:before { /* สร้าง td ขึ้นมาใหม่ข้างหน้าเพื่อแทนคอลั่มน์ด้านบนของ thead */
position: absolute;
top: 6px;
left: 6px;
width: 50%;
padding-right: 10px;
white-space: nowrap;
text-align:left;
font-weight: bold;
}
.tableresponsive td:before { content: attr(data-title); } /* เพิ่ม text เข้าไปใน td:befor จาก attribute data-title ของ td นั้นๆ */
}
การใช้ css แบบในการแก้ไขแบบนี้มีข้อดีคือไม่ต้องไปยุ่งกับ โครงสร้างเก่าซักเท่าไหร่ สำหรับผู้ที่สนใจศึกษา สามารถ Download Source ไปกันได้ครับ