Home  >  Q&A  >  body text

Float a div inside another div

I need a div to float inside another div. Tried using position:fixed but the div now floats outside the parent div.

This is sample code. I need "Div to Float" to float inside "Div 1". Now it floats outside "Div 1" and behind "Div 2"

This is the code.

.wrapper {<!--from  www  .j  av a2s.c  o  m-->
   width:100%;
   height: 200px;
   overflow-y: scroll;
}

.container {
   width: 301px;
  margin: 0px auto;
  height: 1501px;
  background: green;
  position: relative;
}

.element {
   background:yellow;
   position:fixed;
   width:101px;
   height:71px;
   top:51px;
   right:0px;
   left:769px;
   border:2px solid blue;
}
<div class="wrapper">
  <div class="container">
    Div 1
    <div class="element">Div to float</div>
  </div>
</div>
<div class="container" style="margin-top: 30px; background: purple">Div 2</div>

What have I tried?

.wrapper {<!--from  www  .j  av a2s.c  o  m-->
   width:100%;
   height: 200px;
   overflow-y: scroll;
}

.container {
   width: 301px;
  margin: 0px auto;
  height: 1501px;
  background: green;
  position: relative;
}

.element {
   background:yellow;
   position:fixed;
   width:101px;
   height:71px;
   top:51px;
   right:0px;
   left:769px;
   border:2px solid blue;
}
<div class="wrapper">
  <div class="container">
    Div 1
    <div class="element">Div to float</div>
  </div>
</div>
<div class="container" style="margin-top: 30px; background: purple">Div 2</div>

What are my expectations?

I need "Div to Float" to float inside "Div 1".

What is the result now?

Now it floats outside "Div 1" and behind "Div 2"

P粉207483087P粉207483087185 days ago373

reply all(1)I'll reply

  • P粉041881924

    P粉0418819242024-04-04 11:56:41

    .container {
        position:relative;
    }
    .element{
    position:absolute;
    }

    I don't fully understand what you mean by "floating", but this code will place your div.element inside a div.container

    reply
    0
  • Cancelreply