Width of element with position: Absolute (box-Sizing: border-box)

Asked

Viewed 336 times

4

Important: I’m using Twitter Bootstrap, so everything is with box-sizing: border-box.

The difficulty is this: I have an element with absolute positioning. I want its width to be equal to that of the parent element:

div.elemento-filho {
    position: absolute;
    width: 100%;
}

That almost works. My problem is that the element is getting wider than the father, because the width included the margins (margin) of the parent element.

div.elemento-pai {
    width: 180px;
    margin: 0px 15px;
}

In this case, I would like the width of the child element not to consider the margins, that is, to stay measuring 150px instead of 180px.

I can’t fix the width of the child element, as it has to work for parents of different widths.

Is there any way to achieve this? In what way?

  • Without the position: absolute, seems to work. With the position: absolute, is much more than the margin difference. http://jsfiddle.net/ypdtY/

1 answer

2


In this case it is recommended that you use position:relative in the parent element, this will cause the child elements to use it as a basis of calculation.

Example [Jsfiddle]:

HTML

<div id="pai">
    <div id="filho">
    </div>
</div>

CSS

#pai{
    width: 180px;
    margin: 0px 15px;
    border:1px solid red;
    position:relative;
    height:10px;
}

#filho{
    position: absolute;
    width: 100%;
    border:1px solid blue;
}

Links that may be useful: w3schools, maujor

  • 1

    Isn’t that solved?! Just now with your answer I stopped to think, and it really makes sense. I’ve done it to adjust to position of a child element, several times. However, it did not occur to me that it might affect the width. I knew an element with position: absolute is based on the first ancestor with position set to determine your positioning... I have now learned that it bases other attributes than positioning on that same ancestor.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.