I have a page with a title and some content. The header is a dynamic value and can have many different contents depending on the content. This problem occurs when the title is long and requires two or more lines. Since I want the content to stay in the same vertical and horizontal position, I want the last row of the longer title to be in the same vertical position as the first row if the title is shorter.
I hope I can make others understand myself. Please try editing the title by adding a second word and you'll see what I mean.
I think this problem can be solved with flex-box, but I don't know how, I've tried a lot of different things with flex-end etc.
This is my code example:
.main { display: flex; justify-content: center; min-height: 200px; border: 1px solid black; } .wrapper { display: flex; flex-direction: column; align-items: center; border: 1px solid red; width: 200px; height: 300px; padding-top: 20px; gap: 20px; } .header-div { display: flex; border: 1px solid blue; align-items: center; text-align: center; max-width: 100px; } .header { border: 1px solid green; } .content { border: 1px solid green; }
<!DOCTYPE html> <html> <head> <title>Parcel Sandbox</title> <meta charset="UTF-8" /> <link rel="stylesheet" href="style.css"> </head> <body> <div class="main"> <div class="wrapper"> <div class="header-div"> <h1 className="header">Header</h1> </div> <div class="content">Test</div> </div> </div> </body> </html>
Thanks in advance!
edit This is a poorly made image that illustrates my goal. The picture on the left is when the title occupies one line, and the second picture is when the title occupies two lines:
P粉4813668032024-03-23 00:51:03
Change the CSS of the .wrapper class:
.wrapper { display: grid; grid-template-rows: auto 1fr; align-items: center; justify-items: center; border: 1px solid red; width: 200px; height: 300px; padding-top: 20px; gap: 20px; }
Here, we use display: grid to create a grid layout. The grid-template-rows property defines two rows: one for the title and one for the content. The auto value will make the header row adjust to the content height, while the 1fr value will make the content row take up the remaining space. The align-items and justify-items properties center content within their respective lines.
Now, update your HTML so that the h1 element has a class attribute instead of a className attribute:
Parcel Sandbox Header
Test
With these changes, the header will remain on top of the wrapper and the content will remain in the same vertical and horizontal position regardless of the header's length. You can test it by changing the title text to see how it performs at different lengths.