Home > Mobile >  Centering table using CSS
Centering table using CSS

Time:01-24

I have a table that I'm wanting to make center on the screen but nothing is working. I am having trouble figuring out what I need to do or what I have done wrong. Any help would be great.

Here is my css im using:

<style>
table{
    width: 100%;
    height: 900px;
    overflow: auto;
    display: block;
    margin-left: auto;
    margin-right: auto;
      }
</style>

Here is my code for the table:

<table class = 'table table-bordered '>
<tr style='background-color: black; color: white;'>
    <th>ID</th>
    <th>Book-Name</th>
    <th>Author-Name</th>
    <th>Edition</th>
    <th>Status</th>
    <th>Quantity</th>
    <th>Department</th>
</tr>
<?php

while ($row = mysqli_fetch_assoc($result)) {
?>
<tr style = 'background-color: white;'>
    <td><?php echo $row['bid'] ?></td>
    <td><?php echo $row['name'] ?></td>
    <td><?php echo $row['authors'] ?></td>
    <td><?php echo $row['edition'] ?></td>
    <td><?php echo $row['status'] ?></td>
    <td><?php echo $row['quantity'] ?></td>
    <td><?php echo $row['department'] ?></td>
</tr>
<?php
}

?>
</table>

CodePudding user response:

The problem is you are specify the width of the table to 100% which is full screen and at the same time you are using display: block

Two solutions:

By changing width to lower to full screen

By removing the display: block , but I have to notice that you are also setting the height: 900px which will make your table to 900px any ways, you could change it to max-height

table{
    width: 80%;
    height:900px;
    overflow: auto;
     display: block;
    margin-left: auto;
    margin-right: auto;
      }
<table class = 'table table-bordered '>
<tr style='background-color: black; color: white;'>
    <th>ID</th>
    <th>Book-Name</th>
    <th>Author-Name</th>
    <th>Edition</th>
    <th>Status</th>
    <th>Quantity</th>
    <th>Department</th>
</tr>
<?php

while ($row = mysqli_fetch_assoc($result)) {
?>
<tr style = 'background-color: white;'>
    <td><?php echo $row['bid'] ?></td>
    <td><?php echo $row['name'] ?></td>
    <td><?php echo $row['authors'] ?></td>
    <td><?php echo $row['edition'] ?></td>
    <td><?php echo $row['status'] ?></td>
    <td><?php echo $row['quantity'] ?></td>
    <td><?php echo $row['department'] ?></td>
</tr>
<?php
}

?>
</table>

CodePudding user response:

Change your css like this:

table{
  width: 100%;
  overflow: auto;
}

Working example

CodePudding user response:

You can achieve the result this way -->

table {
  position: absolute;
  top: 50%;
  left: 50%;
  transform: translate(-50%, -50%);
}

CodePudding user response:

You could use flexbox. Using width: 100% with margins doesn't make sense.

table {
    display: flex;
    justify-content: center;
    height: 900px;
    overflow: auto;
}
  •  Tags:  
  • Related