Home > database >  Aligning a div to the right side of another div
Aligning a div to the right side of another div

Time:12-27

I want to align a div to the right side of an other div using margin-left: auto; but for some reason this does nothing. If the div is not contained by another div, this approach works flawlessly.

This is an example of the problem:

<!DOCTYPE html>
<html>
<body>
    <style>
        #inner {
            margin-left: auto;
        }
    </style>

    <div id="outer">
        <div id="inner">
            Text
        </div>
    </div>
</body>
</html>

CodePudding user response:

You can add a width to the inner div (#inner) and the margin will take up the remaining space.

#inner {
    margin-left: auto;
    width: 50%;
    border: 1px solid red;
}
  <div id="outer">
      <div id="inner">
          Text
      </div>
  </div>

CodePudding user response:

If there are nested <div> elements, one way to right-align the inner container is to apply a margin-left to the inner <div> element:

<!DOCTYPE html>
<html>
<body>
    <style>
        #inner{
            border: 1px solid red;
            margin-left: 100px;
            height: 50px;
        }
        
        #outer{
            height: 100px;
            border: 1px solid black;
        }
    </style>

    <div id="outer">
        <div id="inner">Text</div>
    </div>
</body>
</html>

  • Related