PHPFixing
  • Privacy Policy
  • TOS
  • Ask Question
  • Contact Us
  • Home
  • PHP
  • Programming
  • SQL Injection
  • Web3.0

Friday, November 18, 2022

[FIXED] How to position child div to the center of every parents div using position absolute in css

 November 18, 2022     centering, css, css-position, html, vertical-alignment     No comments   

Issue

I'm having difficulty on positioning child div's on every parents div.

Here's the css code:

.mainDiv {
   height:500px;
   position: relative;
}

.mainDiv .parent1 {
  height: 250px;
  background-color: blue;
  top: 50px;
  position: relative;
}

.mainDiv .parent2 {
  height: 250px;
  background-color: yellow;
  position: relative;
}


.mainDiv .parent1 .sub1 {
  width: 100px;
  height: 100px;
  background-color: green;
  position: absolute;
  left: 0;
  right: 0;
  margin-left: auto;
  margin-right: auto;
  top: 50%;
}

.mainDiv .parent2 .sub2 {
  width: 100px;
  height: 100px;
  background-color: red;
  position: absolute;
  left: 0;
  right: 0;
  margin-left: auto;
  margin-right: auto;
  top: 50%;
}

Here's the fiddle


Solution

Use transform for that to the child div and it will work!

position: absolute;
top: 50%;
left: 50%;
transform: translate(-50%, -50%);

snippet below:

.mainDiv {
  height:500px;
  
  position: relative;
}

.mainDiv .parent1 {
  height: 250px;
  background-color: blue;
   position: relative;
}

.mainDiv .parent2 {
  height: 250px;
  background-color: yellow;
   position: relative;
}


.mainDiv .parent1 .sub1 {
  width: 100px;
  height: 100px;
  background-color: green;

  position: absolute;
    left: 50%;
    top: 50%;
    transform: translate(-50%, -50%);
    
}

.mainDiv .parent2 .sub2 {
  width: 100px;
  height: 100px;
  background-color: red;
  position: absolute;
    left: 50%;
    top: 50%;
    transform: translate(-50%, -50%);
}
<div class="mainDiv">
  <div class="parent1">
    <div class="sub1">
        
    </div>
  </div>
  <div class="parent2">
    <div class="sub2">
      
    </div>
  </div>
</div>



Answered By - kukkuz
Answer Checked By - Senaida (PHPFixing Volunteer)
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg
Newer Post Older Post Home

0 Comments:

Post a Comment

Note: Only a member of this blog may post a comment.

Total Pageviews

Featured Post

Why Learn PHP Programming

Why Learn PHP Programming A widely-used open source scripting language PHP is one of the most popular programming languages in the world. It...

Subscribe To

Posts
Atom
Posts
Comments
Atom
Comments

Copyright © PHPFixing