I'm trying to center a text in the middle of my screen. For some reason it doesn't work. Can someone please take a look at the following index.html and explain to me what I am doing wrong?
<!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">
<title>Document</title>
<style>
.header {
display: flex;
background-color: black;
padding: 2rem;
}
.outer-container {
display: flex;
flex-direction: column;
justify-content: center;
height: 100vh;
}
.inner-container {
display: flex;
flex-direction: column;
align-items: center;
cursor: default;
justify-content: center;
}
span {
padding: .5rem;
}
</style>
</head>
<body>
<div >
<div >Header</div>
<div >
<div >
<h1>HEADING</h1>
<span>Some text here.</span>
</div>
</div>
</div>
</body>
</html>
I was thinking that the flex-layout fills all available space. Since my flex-direction is "column", I was expecting the outer container to fill the entire height of my screen, but apparently that's not the case.
Update:
I have now placed my outer-container and the inner-container inside a parent-container to showcase the issue I have when setting the height of the outer-container to 100vh: As you can see, the issue is that a height of 100vh for my outer-container is now too much - the correct height would be 100vh minus the height of the header.
CodePudding user response:
add justify-content: center;
on both containers
CodePudding user response:
Your container does not take all screen height and vertical alignment is missing. Here is codepen https://codepen.io/ignasb/pen/KKBQzjQ with vertical and horizontal alignment. I added height and alignment css properties
.outer-container {
height: 100vh;
justify-content: center;
display: flex;
flex-direction: column;
}
Also you might want additional styles if that scrollbar appears.
body {
margin: 0;
}
CodePudding user response:
The quick and dirty solution is to make the containing parent, body
, .outer-container
or some .wrapper
, fill the full viewport and use below CSS to center its content:
display: grid; place-items: center;
snippet
* { outline: 1px dashed } /* for debugging element sizes */
*, ::before, ::after { box-sizing: border-box }
body {
margin: 0; /* remove default margin to prevent overflow */
}
/* REPLACED
.outer-container {
display: flex;
flex-direction: column;
}
*/
.outer-container {
display: grid; place-items: center; /* Easy centering demo */
width: 100%; height: 100vh; /* full screen (or use min-height) */
}
.inner-container {
display: flex;
flex-direction: column;
align-items: center;
cursor: default;
}
span {
padding: .5rem;
}
<div >
<div >
<h1>HEADING</h1>
<span>Some text here.</span>
</div>
</div>