-1

I want the content to be centered vertically and horizontally but it gets centered only horizontally. The problem is that I don't have fixed height. Thank you guys for help!

html,
body {
  height: 100% margin: 0;
  overflow: hidden;
}
.content {
  width: 100%;
  height: 100%;
  align-items: center;
  justify-content: center;
  display: flex;
  flex-direction: column;
  text-align: center;
}
<div class="content">
  <h1>Welcome to the website!</h1>
</div>
Esko
  • 4,109
  • 2
  • 22
  • 37
Daniel Sava
  • 250
  • 3
  • 12

4 Answers4

5

You can easily center an element respect to the parent in this way (assuming that the parent has position: relative;).

In your example:

h1 {
  display: block;
  position: absolute;
  top: 50%;
  left: 50%;
  transform: translate(-50%, -50%);
}

You can also center it in the middle of the screen using position: fixed; instead.

Marco Ferrantini
  • 381
  • 2
  • 10
2

Follow this code

HTML

<body >
  <div class="content">
    <h1>Welcome to the website!</h1>
  </div>
</body>

CSS

html,body {
   height : 100%;
   width : 100%;
}
.content {
   height : 100%;
   width : 100%;
   display: table;
}
h1 {
   text-align: center;
   display: table-cell;
   vertical-align: middle;
}
0

Follow this code.

body{
  margin: 0;
  padding: 0;
}
.content-wrapper{
  background-color: #121212;
  display: block;
  left: 0;
  height: 100%;
  padding: 15px;
  position: fixed;
  top: 0;
  width: 100%;
}
.content{
  background-color: #f5f5f5;
  display: table;
  height: 100%;
  margin-left: auto;
  margin-right: auto;
  text-align: center;
  width: 100%;
}
.centent-cell{
  display: table-cell;
  height: 100%;
  vertical-align: middle;
  width: 100%;
 }
h1{
  color: #121212;
}
<div class="content-wrapper">
  <div class="content">
<div class="centent-cell">
  <h1>Welcome to the website!</h1>
  </div>
</div>
</div>
Rahul
  • 2,011
  • 3
  • 18
  • 31
0

Here's an example of what you need:

<section>
    <div class="centerize">
        <div class="v-center">
            <div class="box">Say my name!</div>
        </div>
    </div>
</section>

and CSS

section {
    height: 100vh;
    background: #fff;
}

.centerize {
    display: table;
    height: 100%;
    width: 100%;
 }

.v-center {
     display: table-cell;
     vertical-align: middle
 }

.box {
     background: #000;
     width: 10%;
     margin: 0 auto;
 }
d3vma
  • 161
  • 2
  • 10