div about another div

1

I want to put one div on top of another, right in the center of the father div

#uno {
  position: relative;
  text-align: center;
}

#padre{
position:absolute;
}
<div id="padre">holaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa como estaaaaaaaaassssssssssssssssssdddddddddddddddddddddddddddddddddddssss
  <div id="uno">cc</div>
</div>
    
asked by hubman 14.08.2017 в 17:16
source

2 answers

4

You are really using the positions backwards. If you want to position a div on another one, you would have to indicate as relative the parent div and as absolute the child so that this will take reference of the first one.

Subsequently, to be able to center it with respect to the father, you can use left: 0 and right: 0 that together with margin: 0 auto will make the div son be positioned in the center of the father. You will have to assign a width to it, otherwise your div child will occupy 100% of the screen.

Finally, if you want the div child to be above the div parent, you can use the property top: 0 to position it at the top of the div parent.

Your modified example:

#padre{
  position:relative;
  background-color: green;
}

#uno {
  position: absolute;
  background-color: red;
  top: 0;
  left: 0;
  right: 0;
  margin: 0 auto;
  width: 20px;
}
<div id="padre">holaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa como estaaaaaaaaassssssssssssssssssdddddddddddddddddddddddddddddddddddssss
  <div id="uno">cc</div>
</div>

If you have questions about how to use the position property, you can consult the question-answer I gave in this other question: What is the difference between position: relative, position: absolute and position: fixed? .

    
answered by 14.08.2017 в 17:54
4

Absolute centering using top, left, right, bottom and margin

#padre {
  background: coral;
  border-radius: 4px;
  height: 100px;
  position: relative;
  width: 100px;
}

#uno {
  background: gold;
  border-radius: 4px;
  left: 0;
  top: 0;
  right: 0;
  bottom: 0;
  margin: auto;
  position: absolute;
  height: 70px;
  width: 70px;
}
<div id="padre">PADRE
  <div id="uno">HIJO</div>
</div>

Absolute centering using left, top and transform

#uno {
  background: gold;
  border-radius: 4px;
  height: 70px;
  left: 50%;
  position: absolute;
  top: 50%;
  transform: translate(-50%, -50%);
  width: 70px;
}

#padre{
  background: coral;
  border-radius: 4px;
  height: 100px;
  position: relative;
  width: 100px;
}
<div id="padre">PADRE
  <div id="uno">HIJO</div>
</div>
    
answered by 14.08.2017 в 17:54