Basically, it is a simple Joke Generator app that gets some text from an API and then puts it in a div container on which I have applied flexbox to center the text, a button, an image, and a title which are inside of it.
However, the container itself is stuck to the top of the page and I am not able to figure out how to center it vertically to the middle of the page since the height of the container depends on the size of the text that it receives from the API.
The issue I am facing:
When I tried to apply display flex to the body and use align-items it is not centering the container vertically based on the viewport's height.
CSS[.scss]:
$primary-color: rgb(33, 41, 53);
$secondary-color: rgb(254, 213, 180);
$tertiary-color: rgb(214, 27, 64);
$hover-color: rgb(65, 76, 93);
$gradient-bg: linear-gradient(to bottom, $primary-color, $tertiary-color);
html {
min-height: 100%; //for the gradient to stretch properly
}
body {
background: $gradient-bg;
box-sizing: border-box;
height: 100%;
display: flex;
justify-content: center;
align-items: center;
}
.container {
min-height: 20rem;
min-width: 5rem;
background-color: $secondary-color;
border-radius: 1.5rem;
margin: 0 5rem;
display: flex;
flex-direction: column;
justify-content: center;
align-items: center;
padding: 1rem 0;
overflow: hidden;
}
HTML:
<body>
<div >
<img alt="" id="ultra-laugh" />
<div ><h1>Joke Generator</h1></div>
<div id="joke"></div>
<button id="joke-button" >Get another Joke</button>
</div>
</body>
Any help is greatly appreciated!
CodePudding user response:
You were so close to having this!
If you are trying to vertically and horizontally center something, set the width and height as you did, and then set the margin-top
and margin-left
to half of what your width
and height
are.
Replace your margin on your container class with this:
margin-top: 10rem;
margin-left: 2.5rem;
Hopefully this helps! :)
CodePudding user response:
In your css code change height value from 100% to 100vh, and that will center verticaly.
html {
min-height: 100%;
}
body {
background: blue;
box-sizing: border-box;
height: 100%;
display: flex;
justify-content: center;
align-items: center;
}
.container {
min-height: 20rem;
min-width: 5rem;
background-color: lightblue;
border-radius: 1.5rem;
margin: 0 5rem;
display: flex;
flex-direction: column;
justify-content: center;
align-items: center;
padding: 1rem 0;
overflow: hidden;
}
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<link rel="stylesheet" href="index.css"/>
<title>Document</title>
</head>
<body>
<div >
<img alt="" id="ultra-laugh" />
<div ><h1>Joke Generator</h1></div>
<div id="joke"></div>
<button id="joke-button" >Get another Joke</button>
</div>
</body>
</html>