Why isn’t my div
element centered?
The div takes all the available space. And you haven’t limited its size. margin: 0 auto;
will only work if the parent is wider than the centered child. margin: 0 auto;
styles the element that has the attribute. If you want to center the table tag inside the div.table, you need to move the style to the table element.
But I want to center not just the table, but also the heading and the “Add” button (that’s why I introduced the div
in the first place), both horizontally and vertically. I don’t think it’s good practice to repeat the same line in separate rulesets for each of the elements. Besides, I don’t want the button to be below the middle part of the table. I want it below the lower left corner of it, as it is now, but move the whole thing to the center of the page, together. How do I do it? (I hope I was clear enough)
Here’s what I achieved so far. How do I center it vertically now?
.table-and-heading, .forms-and-heading {
height: 50%;
width: 50%;
margin: 0 auto;
font-family: Arial, sans-serif;
color: black;
/*border: 4px solid black;*/
}
.table, .forms {
height: auto;
width: max-content;
margin: 2% auto;
/*border: 4px dotted gray;*/
}
h2 {
font-family: 'Roboto Slab', serif;
font-weight: bold;
text-align: center;
}
table {
border: 3px solid black;
}
thead {
background-color: slategray;
}
td {
border-top: 1px solid black;
}
.main-button {
background-color: orangered;
color: white;
}
.main-button:hover {
background-color: hsl(16, 100%, 60%);
}
.delete-button {
color: red;
}
Then you could’ve just set the width to the div rather than the table element.
If you want to center the div horizontally AND vertically, try flexbox. Apply flex to a parent of the div.
The code you posted is not relevant for the positioning of the parent element.