Ayush Gupta
Ayush Gupta

Reputation: 9295

How can I vertically center all children of my div using css?

Here is my code

.header {
        width: 100%;
        height: 100px;
        background: black;
    }
    
    .header .headerContainer {
        position: relative;
    	top: 50%;
        transform: translateY(-50%);
        height: inherit;
    }
    
    img#logo {
        height: 75%;    
    }
    
    p#logotext {
        color: white;
        display: inline
    }
<div class="header">
    <div class="headerContainer">
        <img src="https://cdn.worldvectorlogo.com/logos/react.svg" alt="Logo" id="logo" />
        <p id="logotext">Welcome To Here</p>
    </div>
</div>

However, this is not aligning the elements properly.

How should I modify my CSS so that headerContainer does the alignment properly?

Upvotes: 0

Views: 62

Answers (4)

Lubbock
Lubbock

Reputation: 63

so close .... you just need to put dispaly : flex; into headerContainer

.header {
  background: black;
  height: 100px;
  width: 100%;
}
.header .headerContainer {
  align-items: center;
  display: flex;
  height: inherit;
}
img#logo {
  height: 75%;    
}
p#logotext {
  color: white;
  display: inline
}

Upvotes: 0

Luke Paoloni
Luke Paoloni

Reputation: 174

You can also use CSS Grid.

.header {
  background: black;
  height: 100%
  width: 100%;
  padding: 20px;
}
.header .headerContainer {
  display: grid;
  grid-template-columns: 1fr 1fr;
}
img#logo {
  width: auto;
  height: auto;
  align-self: center;
}

p#logotext {
  color: white;
  align-self: center;
}
<div class="header">
    <div class="headerContainer">
        <img src="http://via.placeholder.com/350x150" alt="Logo" id="logo" />
        <p id="logotext">Welcome To Here</p>
    </div>
</div>

Upvotes: 0

Shaik
Shaik

Reputation: 378

Use This Code

<style>
.class{
Position:absolute;
top:50%;
left:50%;
transform:rotateX(-50%,50%);
}
</style>

Upvotes: 0

Sebastian Brosch
Sebastian Brosch

Reputation: 43594

You can use flexbox to solve this:

.header {
  background: black;
  height: 100px;
  width: 100%;
}
.header .headerContainer {
  align-items: center;
  display: flex;
  height: inherit;
}
img#logo {
  height: 75%;    
}
p#logotext {
  color: white;
  display: inline
}
<div class="header">
    <div class="headerContainer">
        <img src="https://placehold.it/50x50" alt="Logo" id="logo" />
        <p id="logotext">Welcome To Here</p>
    </div>
</div>

So you don't need to use position or tranform to vertical center the items. If you want to learn more about flexbox I recommend this site for a quick overview / reference.

Upvotes: 3

Related Questions