salbeira
salbeira

Reputation: 2611

Position HTML element absolutely but have it's 100% width be that of the parent

For example I want to create a footer for the page. It should always be at the bottom, so I would use:

footer {
    position: absolute;
    bottom: 0;
}

But I want the footer to always have a top border to mark it as such:

[...]
    border-style: solid;
    border-top: 1px;
    border-color: gray;
[...]

The problem now is that if the footer is very small, it's border will always be just it's content's width.

If I want to extend the width of the element to it's parent's width, using width: 100%;, it get's extended to the right to the far edge of the screen. width: auto; extends it only as far as needed, but I want it to be at least filling the parent.

What I want is it to be absolutely positioned at the bottom of it's parent, but not have the "detached" width calculation that absolute positioning has on the width value. I do not want to attach a different "max-width" value to each element depending on what parent such a width-filling footer should have.

Example html:

<html>
    <body>
        <article>
            <section>Lorem Ipsum</section>
            <footer>
                <a href=www.example.com>Link</a>
            </footer>
        </article>
    </body>
</html>

Example css:

article {
    width: 600px;
    margin: auto;
}

article footer {
    width: 100%;
    position: absolute;
    bottom: 0;
}

Upvotes: 0

Views: 197

Answers (1)

Danny
Danny

Reputation: 1113

You could solve this issue by setting the left offset value to 0:

footer {    
    bottom: 0;
    left: 0;
    position: absolute;
    width: 100%;
}

You would then need to set container element that you want to position the footer in to have a position of value relative

.container {
  width: 500px;
  height: 500px;
  position: relative;
  margin: 0 auto;
  border: 1px solid black;
}

footer {
  position: absolute;
  bottom: 0;
  width: 100%;
  left: 0;
  background: green;
  
 }
<div class="container">
  container
  <footer>
    footer
  </footer>
 </div>

Upvotes: 1

Related Questions