PHP是一种广泛使用的服务器端脚本语言,尤其适用于Web开发。在Web页面中,表格(table)是一种常见的布局元素,用于组织和展示数据。表格内的文字居中是指将表格单元格(cell)中的文本内容水平居中对齐。
以下是一个简单的PHP示例,展示如何在HTML表格中将文本居中:
<?php
// PHP代码可以用来生成动态内容
$titles = ["Name", "Age", "City"];
$data = [
["John Doe", 30, "New York"],
["Jane Smith", 25, "Los Angeles"]
];
?>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>PHP Table with Centered Text</title>
<style>
table {
width: 100%;
border-collapse: collapse;
}
th, td {
border: 1px solid #ddd;
padding: 8px;
text-align: center; /* 水平居中 */
vertical-align: middle; /* 垂直居中 */
}
th {
background-color: #f2f2f2;
}
</style>
</head>
<body>
<table>
<thead>
<tr>
<?php foreach ($titles as $title): ?>
<th><?php echo htmlspecialchars($title); ?></th>
<?php endforeach; ?>
</tr>
</thead>
<tbody>
<?php foreach ($data as $row): ?>
<tr>
<?php foreach ($row as $cell): ?>
<td><?php echo htmlspecialchars($cell); ?></td>
<?php endforeach; ?>
</tr>
<?php endforeach; ?>
</tbody>
</table>
</body>
</html>
<style>
标签中正确设置了text-align: center;
和vertical-align: middle;
。<td>
标签中。通过以上方法,可以有效地解决PHP表格内文字居中的问题,并确保在不同设备和浏览器上都能正确显示。
领取专属 10元无门槛券
手把手带您无忧上云