将从外部php文件创建的项居中

Center items that are created from an external php file

本文关键字:文件创建 从外部 php      更新时间:2023-09-26

我有一个表格,我想放在我的网页中心。html文件从php文件加载一个表,但由于某种原因,即使将中心块作为一个类(使用bootstrap),也不会发生任何事情。这张桌子装得很好,只是没有居中。

HTML:

<script>
  $(document).ready(function(){                          
    $(".mytable").load('pastmoods.php');                         
  });
</script>
<div class = "mytable center-block" style="text-align:center"></div>

PHP:

$query = mysqli_query($db_connection, "SELECT * FROM DemoUser");
$fields_num = mysqli_num_fields($query);
echo "<h1>Past Moods: {$table}</h1>";
echo "<table border='1'><tr>";
// printing table headers
for($i=0; $i<$fields_num; $i++)
{
  $field = mysqli_fetch_field($query);
  echo "<td>{$field->name}</td>";
}
echo "</tr>'n";
// printing table rows
while($row = mysqli_fetch_row($query))
{
  echo "<tr>";
  // $row is array... foreach( .. ) puts every element
  // of $row to $cell variable
  foreach($row as $cell)
    echo "<td>$cell</td>";    
  echo "</tr>'n";
}
mysqli_free_result($query);
 echo "<table border='1' align='center' width='xxx'><tr>";

试试这个。

根据@Aashray 的建议进行编辑

您可以为div使用固定宽度,并使用文本中心引导类,而不是内联样式。

根本不要使用center。坚持css。将表放在"div"或"span"中,并用css居中,确保您已经按照Sachi上面提到的那样设置了边距。

您的表是向左浮动还是向右浮动?这可能是个问题。确保它有浮动:上面没有浮动,或者根本没有浮动。

此外,请确保表的父元素有空间让表位于其中心。例如,如果表及其父元素的内部宽度相同,则表将没有空间居中。

确保桌子没有宽度:100%,因为它将在没有居中的情况下适合其父桌子。

我想你需要这里的CSS:

.mytable.center-block {
    margin: 0 auto;
}

这取决于<div class="mytable center-block style="text-align"></div>所在的容器。

例如,这将根据父div:将表格居中

HTML

<div class="parent-div">
    <div class="mytable center-block"></div>
</div>

CSS

.parent-div {
    width: 1000px; /* Let's say for this example the parent-div is 1000px wide */
    height: 400px; /* Some height, just to give it dimension */
}
.mytable.center-block {
    margin: 0 auto; /* Centers the table within the parent-div */
}

当然,这是考虑到表的宽度小于1000px,为了这个例子,我假设了这一点。如果这有帮助,请告诉我。

编辑:还需要注意的是,将HTML元素放在<script>标记下面不是一种好的做法。理想情况下,<script>标签应位于标头内或结束正文标签</body>之前。