Ash
Ash

Reputation: 1326

Why is width:100% relative to screen when within media query

If I have want to have the following layout:

[----foo-----][[-bar1-][bar2]]

I.e. two columns each half the width, and then in the second column two sub-column with a 3/5 and 2/5 split, I do something like:

<div>
  <div id="left-section" class="half-width">
     Foo <!-- lots of content -->
  </div>
  <div id="right-section" class="half-width">
     <div id="three-fifths-of-this-section" class="three-fifths-width">
          Bar1 <!-- lots of content -->
     </div>
     <div id="two-fifths-of-this-section" class="two-fifths-width">   
          Bar 2 <!-- lots of content -->
      </div>
  </div>  
</div>

with the following CSS

div {
    display: inline-block;
}

@media screen and (min-width: 48em) {
  .half-width {
    width: 50%;
    *width: 49.9690%;
  }


  .three-fifths-width {
    width: 60%;
    *width: 59.969%
  }

  .two-fifths-width {
    width: 40%;
    *width: 39.9690%;
  }
}

Why is the three-fifths-width class computed as 60% of the screen width (and two-fifths-width as 40% of the entire screen)? It's just a regular CSS width property which should be 60% (or 40%) of the parent element and so 30% (10% resp.) of the screen in practice.

By the way I am actually using PureCSS in practice but I'm interested in the underlying CSS.

Also, I aware that the min-width within the @media query is always relative to the screen, I'm asking about a regular width or even min-width as a CSS rule within the scope of a @media query.

Upvotes: 1

Views: 1214

Answers (1)

Paul
Paul

Reputation: 9022

I am not sure how your browser renders your output, but first of all it shouldn't be anywhere near 60% or even 30% due to the fact that you apply

display: inline-block;

to all div elements.

This causes two things: (1) your divs will only be as wide as necessary to display its content and (2) whitespace between inline elements may cause unwanted effects. Therefore, your example looks like this: http://jsfiddle.net/8jrewj71/.

Note, that I have added your code twice and applied different classes to the parent div to see the difference between your CSS being inside a media query and not.

Now, if we add

.media, .nomedia { display: block; }

we get a complete different picture: http://jsfiddle.net/n4aw8pcd/

As long as the preview/result window is small enough, the media query part looks like before. However, as soon as the viewport exceeds 48em, it looks exactly the same as the part without media queries below.

Long story short: The answer to your question must be, it doesn't. width: 100%; is relative to the next parent element with a width property.

Upvotes: 1

Related Questions