I’m creating a vijesti.html page with a CSS Grid layout for displaying three types of news items:
Main News (.mainNews) spans the full width. It should have a 1:2 aspect ratio on screens wider than 800px, and 1:1 on smaller screens.
Vertical News (.verticalNews) is 25% width on screens wider than 800px, 50% on smaller screens, and its height is always double the width.
Square News (.squareNews) has equal width and height, taking up 25% width on large screens and 50% on smaller screens.
I’m trying to use grid-template-areas for this but getting "Invalid property value" errors. How can I properly set up grid-template-areas for this layout, or is there a better approach?
This is the code I’ve written for it :
<body>
<div class="news">
<div class="mainNews">Vijest</div>
<div class="verticalNews">Vijest</div>
<div class="squareNews">Vijest</div>
<div class="squareNews">Vijest</div>
<div class="squareNews">Vijest</div>
<div class="squareNews">Vijest</div>
<div class="verticalNews">Vijest</div>
<div class="squareNews">Vijest</div>
<div class="squareNews">Vijest</div>
<div class="squareNews">Vijest</div>
<div class="squareNews">Vijest</div>
<div class="verticalNews">Vijest</div>
<div class="verticalNews">Vijest</div>
</div>
</body>
body {
background-color: #cdc3a9;
font-family: Arial, sans-serif;
margin: 0;
padding: 0;
}
.news {
margin: 0;
display: grid;
grid-template-columns: 1fr 1fr 1fr 1fr;
grid-gap: 10px;
grid-template-areas:
"main main main main"
"vertical square square vertical"
"vertical square square vertical"
"square square vertical vertical"
"square square vertical vertical"
}
.mainNews {
grid-area: main;
background-color: #c9daf8;
}
.verticalNews {
grid-area: vertical;
background-color: #fff2cc;
}
.squareNews {
grid-area:square;
background-color: #f4cccc;
}
I plan on adding media query later, my first step was to solve this.
2
Answers
You are missing a ; at the end of your last template area line.
You also have a major problem with your areas layout.
According to the mdn for grid-template-areas documentation: "Unless those cells form a rectangle, the declaration is invalid".
For example, you could change your areas to:
grid-template-areas:
Of course, you’ll have to work out the area names and use based on how you want your layout to work.
This is my suggestion, the detailed explanation is at the bottom.
HTML Structure:
CSS:
Explanation:
aspect-ratio
is used for each type of news item to control its width-to-height ratio. For example,.mainNews
has a 2:1 aspect ratio on wider screens and changes to 1:1 in the media query for screens smaller than 800px.grid-template-columns: repeat(2, 1fr);
)..mainNews
and.verticalNews
elements spanning the full width.grid-template-areas
is designed to create a basic grid template layout, it doesn’t automatically account for individual, repeated elements likesquareNews
andverticalNews
. These items are styled according to their class but are placed in the grid using the defined areas.