I have a sidebar with position fixed and have been trying to center a table between the edge of the sidebar and the edge of the screen, a task I would never have thought would cause me this much trouble. Here is my code:
* {
margin: 0;
padding: 0;
list-style: none;
}
body {
background-color: #292929;
}
.sidebar-menu {
background-color: #0A0A0A;
display: flex;
flex-direction: column;
width: 100px;
position: fixed;
height: 100%;
padding: 20px;
padding-bottom: 100px;
justify-content: top;
align-items: center;
border-right: 3px solid #1098F7;
}
.sidebar-items {
margin: 40px 0;
}
.sidebar-items:hover {
color: #1098F7;
}
#sidebar-logo {
color: #1098F7;
font-family: "Raleway", sans-serif;
font-weight: 900;
font-size: 40px;
margin-top: 400px;
user-select: none;
}
.fa-solid {
color: white;
}
.fa-solid:hover {
color: #1098F7;
}
table {
font-size: 30px;
color: white;
border-collapse: collapse;
font-family: "Roboto", sans-serif;
font-weight: 700;
min-width: 1300px;
}
<div class="sidebar">
<ul class="sidebar-menu">
<li class="sidebar-items"><a href=""><i class="fa-solid fa-plus fa-4x"></i></a></li>
<li class="sidebar-items"><a href=""><i class="fa-solid fa-chart-simple fa-4x"></i></a></li>
<li class="sidebar-items"><a href=""><i class="fa-solid fa-hourglass-half fa-4x"></i></a></li>
<h1 id="sidebar-logo">HMH</h1>
</ul>
</div>
<div class="table-container">
<table>
<thead>
<tr>
<th>header1</th>
<th>header2</th>
<th>header 3</th>
<th>header 4</th>
</tr>
</thead>
<tbody>
<tr>
<td>1</td>
<td>10</td>
<td>1000</td>
<td>1000</td>
</tr>
</tbody>
</table>
</div>
Me and chatgpt have been having multiple arguments over how to do this, and each time it gives me new code either it has made the sidebar scrollable, or the table is centered based on the full screen not from the edge of the sidebar, so there is not even whitespace each side.
Making the body a flexbox has been the most common suggestion but I just cannot get it to work.
Also to note a somwhat similar question has been asked but I have tried to implement the solutions and am facing the problem of sidebar scroll again.
Any help much appreciated, thank you.
2
Answers
You know the width of the sidebar exactly as you have set it (100px + 2 * 20px padding).
So you can position table-container to be left by 140px. And can give it a width of 100vw less 140px (assuming that is what you are aiming for).
In this snippet the table is centered with the good old-fashioned
margin: 0 auto
Of course, given the large min-width on the table this is only for fairly large viewports. I assume you have a different layout/set of width constraints for narrower viewports.
I made many changes to the code. You can check below codes.
Also you can control with codepen: https://codepen.io/yusufdogandev/pen/bGmpLZR