ในการสร้างกริดแบบขยายด้วย CSS และ JavaScript โค้ดจะเป็นดังนี้ -
ตัวอย่าง
<!DOCTYPE html> <html> <head> <meta name="viewport" content="width=device-width, initial-scale=1" /> <style> body { padding: 1%; font-family: "Segoe UI", Tahoma, Geneva, Verdana, sans-serif; } * { box-sizing: border-box; } .left, .right, .center { float: left; width: 33%; color: white; padding: 10px; height: 200px; text-align: center; } .left { background-color: tomato; } .right { background-color: teal; } .center { background-color: rgb(166, 71, 255); } .container:after { clear: both; } .closebtn { float: right; color: white; font-size: 35px; cursor: pointer; } .closebtn:hover { transform: scale(1.5); } .containerTab { padding: 20px; width: 99%; color: white; } </style> </head> <body> <h1 style="text-align: center;">Three Column grid example</h1> <div class="container"> <div class="left" onclick="openTab('tab1');" ;> <h1>Some text on the left</h1> </div> <div class="center" onclick="openTab('tab2');"> <h1>Some text in center</h1> </div> <div class="right" onclick="openTab('tab3');"> <h1>Some text on the right</h1> </div> </div> <div id="tab1" class="containerTab" style="display:none;background:tomato"> <span onclick="this.parentElement.style.display='none'" class="closebtn">×</span> <h2>Tab 1</h2> <p> Lorem ipsum dolor sit amet, te quo doctus abhorreant, et pri deleniti intellegat, te sanctus inermis ullamcorper nam. Ius error diceret deseruisse ad </p> </div> <div id="tab2" class="containerTab" style="display:none;background:rgb(166, 71, 255)"> <span onclick="this.parentElement.style.display='none'" class="closebtn">×</span> <h2>Tab 2</h2> <p> Lorem ipsum dolor sit amet, te quo doctus abhorreant, et pri deleniti intellegat, te sanctus inermis ullamcorper nam. Ius error diceret deseruisse ad </p> </div> <div id="tab3" class="containerTab" style="display:none;background:teal"> <span onclick="this.parentElement.style.display='none'" class="closebtn">×</span> <h2>Tab 3</h2> <p> Lorem ipsum dolor sit amet, te quo doctus abhorreant, et pri deleniti intellegat, te sanctus inermis ullamcorper nam. Ius error diceret deseruisse ad </p> </div> <script> function openTab(tabName) { var i, x; x = document.querySelectorAll(".containerTab"); Array.from(x).forEach(item => { item.style.display = "none"; }); document.getElementById(tabName).style.display = "block"; } </script> </body> </html>
ผลลัพธ์
รหัสข้างต้นจะสร้างผลลัพธ์ต่อไปนี้ -
เมื่อคลิกที่ div ใด ๆ -