output I am creating a menu page with three containers: chicken, beef, and sushi. However, after writing the CSS code, the boxes appear uneven. Here is my CSS code:
* {
box-sizing: border-box;
}
body {
background-color: white;
}
h1 {
text-align: center;
font-family: cursive;
}
div{
border: 1px solid black;
width: 300px;
float: left;
margin: 20px;
}
I need help figuring out why the containers are uneven and how to fix it.
2
Answers
You have two options:
overflow: scroll
fordiv
selector, like this:This is simple with no too much modifications to your code. The boxes has the same height (300px), but if contents of one div do not fit in this height they are hidden and can be viewed by scrolling.
Note that we removed
float: left
. Also note that it is better to use class selectors instead of element selectors (note replacment ofdiv {
with.box {
), avoid element selectors as possible.Why not use float?
The use of the
float: left
property was popular in the past for website layout, but it is now considered a less recommended method. The use of float often causes problems in modern web design. Therefore, it is recommended to choose other methods such as CSS flexbox or CSS grid. These provide much more options and compatibility in layout design.Flex
With the
display: flex
property, child elements can be arranged in one row or one column. In this case, they achieve equal height regardless of scrolling. It is a better solution than a fixed height, such as 300px, because when applying short texts, the scroll bar will never appear, yet they will still have the same height.If we want to compare flex to grid, perhaps the most straightforward way to do it is by saying that flex is a single-column or single-row grid table.
Grid
With the
display: grid
setting, we essentially get a table built from a specified number of columns or rows, with uniform height and width. This is commonly used, for example, in displaying image galleries or file managers.Solution (with flex)
More information
CSS –
display: flex
– MDNCSS –
display: grid
– MDN