Andrew Latham
Andrew Latham

Reputation: 6132

% width puts element outside container, same px width keeps it inside

I have a div that I am trying to place inside of another div. The pink div is the container and the red div is mine. My div contains an internal div that is 44px wide. The css properties of my div are float: right, text-align: center, box-sizing: border-box, and border-collapse: collapse. When I set width: 44px, I get the following result:

enter image description here

When I set width: 15%, however, the box floats to the edge of the screen instead of to the edge of the containing div. No other property is being changed between these two pictures.

enter image description here

What is the explanation for this behavior?

JsFiddle: http://jsfiddle.net/xU9RV/

Upvotes: 0

Views: 42

Answers (1)

user1583190
user1583190

Reputation:

One important aspect of how widths in percentage are working, is that they depend on the width of the parent element.

<div style="width: 100px; height: 100px; background-color: blue;">
  <div style="float: right; width: 15%; background-color: pink;">
    <div style="width: 44px; height: 44px; background-color: red;">
    </div>
  </div>
</div>

As you can see in your code here you set the first div to be 100px wide. The second div is set to 15% and as percentage is dependant on the parent width, it's only 15px wide. So when the third div comes with 44px width it will overflow the parent container and show as if it was half way outside the first div.

To get the same width of the percent as the pixel value, you have to use 44% of the 100px the parent is.

So when working with widths it's important to keep in mind that percentage are dependent on it's parents width.

Upvotes: 1

Related Questions