CodeinWP CodeinWP

What Does “width: 100%” Do in CSS?

What Does width: 100% Do in CSS?It seems like this should be one of the easiest things to understand in CSS. If you want a block-level element to fill any remaining space inside of its parent, then it’s simple — just add width: 100% in your CSS declaration for that element, and your problem is solved.

Not so fast. It’s not quite that easy. I’m sure CSS developers of all skill levels have attempted something similar to what I’ve just described, with bizarre results ultimately leading to head scratching and shruggingly resorting to experimenting with absolute widths until we find just the right fit. This is just one of those things in CSS that seems easy to understand (and really, it should be), but it’s sometimes not — because of the way that percentages work in CSS.

Use box-sizing: border-box

This was originally an older post that didn’t take into consideration possible use of the border-box property. If you add the following at the top of your CSS file, you should be able to avoid many of the problems inherent in using 100% width on your elements:

* {
  box-sizing: border-box;
}

This ensures padding is factored into the width of your elements. Of course, not all projects use this and this doesn’t fix the fact that margins can affect the position of an inner element. But in most cases, I strongly recommend you use padding inside a box, rather than margins, to ensure you don’t have this problem.

Blocks Don’t Need 100% Width

When we understand the difference between block-level elements and inline elements, we’ll know that a block element (such as a <div>, <p>, or <ul>, to name a few) will, by default expand to fit the width of its containing, or parent, element (minus any margins it has or padding its parent has).

A Block-Level Element Expands Naturally

Most CSS developers understand this concept pretty well, but I thought it would be useful to point it out here as an introduction to explaining how percentages work when used on the width property.

What width: 100% Really Means

When you give an element a width of 100% in CSS, you’re basically saying “Make this element’s content area exactly equal to the explicit width of its parent — but only if its parent has an explicit width.” So, if you have a parent container that’s 400px wide, a child element given a width of 100% will also be 400px wide, and will still be subject to margins, paddings, and borders — on top of the 100% width setting. The image below attempts to illustrate this:

The child's content area will equal the parent's

And of course, the exact same rule would apply to any percentage value. The content area will be the percentage of the parent’s explicitly-set width setting.

NOTE ADDED: The width of the child’s content area will equal the width of the parent’s content area, but will not move outside the parent unless its own padding or margins are affecting it. Thanks to the comment by Fabio Brendolin for clarifying this.

Should it Ever Be Used?

In many cases, applying width: 100% to a block level element is either unnecessary or will bring undesirable results. If you’re using padding on the inner element and you use box-sizing: border-box, then you’ll be safe.

One case where you might use width: 100% is when the element is inheriting a set width value that you want to override. But even in this case, a better option would be to use “width: auto”, which is the default for block elements.

The other instance where this is necessary is when using flexbox, which sometimes requires that an element be set to 100% width in order to take up a full line and override flexbox’s natural manner of spacing elements evenly on a single line. But this depends on what layout you’re trying to achieve.

Height Works the Same Way (in All Browsers!)

And this little lesson provides a reminder of one of the frustrating things about CSS layouts — that you can’t give an element a height that fills its parent, unless the parent is given (you guessed it) an explicit height setting. The only difference is that in this case “auto” will not work, but instead “height: 100%” is required.

And the great part is that all browsers (even IE6 and IE7) use percentage height exactly the same (IE bugs excluded), so as long as you explicitly set a height on the parent, the child element will fill the height to 100% as expected.

What do you think? Have you ever misinterpreted percentage widths, and abandoned using them because they didn’t work as you expected? I know I’ve done this, and it took me quite some time to get it right and understand them better.

94 Responses

  1. bhoot says:

    Eye opening insight! :)

  2. wongpk says:

    I normally apply overflow:hidden instead of height… But to help in IE6, height:100% sometimes is a helpful little mate :P

    • The overflow:hidden solution is for floats, and is used on a parent element whose height is unknown, so that’s really a different issue than what I’m discussing here (although somewhat related).

      What you’re referring to is “clearing floats” which is a different topic.

      • Sean says:

        If I understand it right clear float is automatic in most modern browsers right?

        • No, not at all. Clearing floats is always necessary, and will always be necessary — until we learn to use the new layout features in CSS3 that don’t require floats.

          But because of the nature of floats (the fact that they are removed from the flow), clearing will always be needed in certain circumstances.

  3. Tanmay Joshi says:

    Being a new developer it was really good to know.

    Thanks,
    Tanmay

  4. David says:

    I’ve been developing sites for a long, long time now, and I still occasionally get bitten by little things like relative widths. This is a good, simple write-up to point people to. :)

  5. Hi Louis, actually i guess this won’t happen in the given example, because the padding will be added to the width changing the final width.

    But It will happen if your parent element has an explicit width (like the example) and its child has width: 100% AND margins or paddings set. In this cases using with: auto in the child solves the problem!

    PS: But only in majors browsers cause on IEs the parent container will have his width plus the child’s adjacent space and the “moving” won’t happen.

  6. Donald Allen says:

    If you’re targeting a specific browser or platform (say iPhone/iPad/iPod Touch MobileSafari), you could use the -webkit-box-sizing set to border-box and not worry about it!

  7. Zlatan Halilovic says:

    Hmmm, if I recall right, I’ve used the 100% value in the width property a few times, when my div element had fixed positioning, but other than that, I didn’t find any good use of it. But I’m sure that I would eventually run into problems with it if it weren’t for this article, so I give a big thanks to the author for informing me like this :)

  8. Jae Xavier says:

    Cool. That clears up my understanding.

  9. Alex says:

    Well, I didn’t know that. Well explained part with the child overlap.

  10. memo says:

    I have no idea 100% could mean so much. Nice article!

  11. Vimal says:

    Really an excellent read! Thanks a lot for sharing the info :)

  12. clervius says:

    This is a very good idea to have posted this. I came across this same issue in my last design where I had the child div set to 100% and I had all kinds of margins and paddings on the parent div. I couldn’t figure out for the life of my why the child div was not behaving! I ended up removing the width:100%; and it worked… But I couldn’t figure out why..

    Now I do. :-)

  13. JeffreyPia says:

    Great article! I was struggling with this exact issue yesterday. I’d like to hear more about practical applications for using percentages. What some situations in which they should be used? Also, how does the above change when dealing with floating and inline elements?

  14. Davidmoreen says:

    Very interesting, this is why I am sometimes in love with modern browser… Easy fixes.

  15. Heam says:

    Good job , Keep going

  16. Good basics – the important detail where the content moves outside the box might easily be overlooked.

  17. Matt says:

    Great Article. I know I have done this when I was starting out. Hopefully no clients come calling me out. Cheers!

  18. yeey i’m a little smarter now thanks

  19. John Manoah says:

    In all these, making sure the HTML doc type is set to “Strict” elimates the majority of CSS problems… This is my experience so far!

  20. David Workman says:

    Yeah, it’s one of the parts that is clear once you grok the CSS box model, but is confusing to people who are new to CSS.

    It’s also something that CSS3 is looking to correct as there will be the ability to set the box model using CSS3 styles. This will let you change the behavior of ‘width:100%’ to mean ‘the total width should be 100% of the parents width’ rather than ‘the content box width should be 100% of the parents width’. That said, I expect ‘auto’ will still be the better value to use in the majority of cases where a newcomer would want to put ‘width:100%’ :)

  21. Edison A. Leon says:

    Thank you so much for the tip, I finally get it!

  22. Hans Nordhaug says:

    “[…] as long as you explicitly set a WIDTH on the parent, the child element will fill the HEIGHT to 100% as expected.”

    A small typo?

  23. Amol says:

    Really nice article.

  24. Eureka says:

    I like your idea

    element {
    width: remainder; /* not valid, but I wish it was! */
    }

    You can write a little jQuery plug-in to solve this problem

    • subduedjoy says:

      You don’t even need a JQuery plugin. It takes very little JavaScript code to calculate the remaining width (or height for that matter) of the last element and set it accordingly. I, too, wish we could do it with CSS.

  25. on width:remainder

    In the case of floating elements you could simply put a margin (in the direction of the floats) on the block element spanning the total width of the floats and you pretty much have what you want there.

    Good article though, it’s one of those simple things many people seem to miss and you’re right that it stems from a lack of understanding what block and inline really mean. It took me a long time to figure that one out, even though it’s one of the most basic css properties.

  26. Vectorbunker says:

    Nice share.. Keep going

  27. Gustavo Melo says:

    Good to know about that !
    Well done.

  28. Neo says:

    Thanks for clarifying and especially important for when it comes to creating flexible layouts. I’ve been experimenting with % values for widths and noticed what you’ve highlighted – a “remainder” value would’ve been ‘sweeet’!

  29. Eric says:

    Great post! I mainly have problems with css height. You are correct that 100% height will only work if the parent has a set height percentage, however, I typically have strange results between FF, IE7 and IE8, especially with multiple nested blocks. Generally speaking, though, this is some good info.. thanks for posting!

  30. Ed at Kliky says:

    Pretty successful post on such a seemingly simple subject. This thing’s all over the design tweets. All in all, a good read.

  31. Dan says:

    I find width: 100% when I center an element horizontally. If not, I have to match the width of a child to it’s parent. Wouldn’t width: 100% make sense in this case?

  32. Jamp Mark says:

    how i wish there’s something that makes child fill up remaining parent height.
    nice article by the way

  33. Ken the tech says:

    Like Jamp just said before of me, I wish there to be a CSS property for a div to keep the height as it’s parent. Unfortunatelly using js/jq is the only way.

    regarding width:100%; I prefer using block elements like DIVs, paragraphs etc instead of using 100%. Not sure how 100% is working in IE6 though.

    Interesting article :)

  34. csssample says:

    Excellent Article, Keep posting like this

  35. Sayz says:

    This is a good explanation, before I was obsessed with the width 100% because, well I don’t understand what it means. And I understand this intuitively because of trial and error. But you explain it very well here. Nice article.

  36. designi1 says:

    Ahaha “I Don’t Have a Fancy Footer. Sick.”

    Great article. That´s a little important thing when you start developing. Thanks.

    and you do not have a fancy footer but you have a footer great humor on it :D

  37. Jon Spooner says:

    wow thank you so much for the graphic explaining the inherited width and how it breaks out of the parent box! Without explicit borders on the boxes it is hard to understand what is going on when this bit me in the past. Now I finally get it! Thank you!

    JS

  38. super_lame_dev says:

    ok, but what can we do if we want a div to fit 100% (as we intend to) heigth of another element?
    es: i want a div inside a cell () to fit it in heigth. how can i do that ?

    • You have to make sure the parent element has a specified height (for example “height: 300px”. As long as that is true, then if you set “height: 100%” on the child element, it will fill it.

      But that’s where the problem comes in, as mentioned in the article: In most cases, you don’t have (or want) a parent container to have a set height, so the “height: 100%” doesn’t do anything. There are workarounds for that, but they are complicated, and beyond what I can explain in this comment.

  39. colinbashbash says:

    That makes a lot of sense with problems i’ve had before… but… it seems to not work like that always… why?

    Example HTML where it looks like the 100% width ends up being the same as width-auto:

    [!DOCTYPE html]
    [html]
    [head]
    [style type=’text/css’]
    .d1,.d3{width:400px;height:400px;padding:10px;border:solid 2px red;}
    .d2{width:100%;height:100%;border:solid 1px green;}
    .d4{width:auto;height:100%;border:solid 1px green;}
    [/style]
    [/head]
    [body]
    [div class=’d1′]
    [div class=’d2′]
    hello
    [/div]
    [/div]
    [div class=’d3′]
    [div class=’d4′]
    hello
    [/div]
    [/div]
    [/body]
    [/html]

    • Colin, in the example you’ve given here, you’re using “padding” on the parent to separate the child from the parent. So, the parent element expands to suit the padding. In other words, padding does not affect the width of the content area, so the child element will still fit inside the content area just fine. But you’ll notice if you change the “width: 100%” to “auto”, there will be a slight change, because of the border setting.

      The problem arises when you use margins on the child element. Then in that case, specifying “width: 100%” would cause the child to push outside the content area of the parent in an undesirable way.

  40. Jennifer R says:

    Of course, I only use Width parameter when the object does not have a width I like :)

  41. Flyingtgr says:

    How about using left = 0 and right = 0?

  42. Interesting.
    I know this is an older post, but it’s new to me! So I thought I’d let you know that there actually are some uses for width: 100%; off the top of my head, I can only think of one, and that’s tables.

    Tables, because they have their own box model (not block or inline), do NOT automatically expand to fill their containing element, but drop in some width: 100%; and voila! Wall-to-wall!

  43. Ryan says:

    That’s how the box model works, border & padding get added to the width. However you can make browsers behave like IE8 naturally does by applying the box-sizing property e.g.

    -moz-box-sizing: border-box;
    -webkit-box-sizing: border-box;
    box-sizing: border-box;

    • Wayne says:

      nesting divs also works

      <div style=”padding:10px” comment=”padding color is parent color”>
      <div style=”background:#963″ comments=”div color does not extent into padding”>
      foo bar
      </div>
      </div>

  44. I just feel great that I got to go through this article. Really helpful to better understand the:

    width: 100%;

  45. Wayne says:

    Searching in hopes somebody had a better solution.

    I would like to theme a template with a centered 960px divide (which needs the width) with a logo of unknown width to float left in this 960 divide. Then “because the menu bar has a background”, it needs to take up the remainder of the space without becoming to wide and dropping below the logo.

    Looks like I need to place a background on the 960 wrapper, that gets covered up by a background for the logo div.. Then the menu bar wrapper only has an image on the left to cover up the 960 wrapper background so the left edge of the menu is correct. And the menubar wrapper will only use the space needed letting the menubar graphics on the right edge of the 960 layout be filled in by the background wrapper. I can do this but I pity the fool who wants to change the menu bar graphic.

  46. Alex says:

    Thank you for writing this. It really helped me to understand css widths better. Much appreciated.

  47. David says:

    I use CSS width:100%; to scale images to fit into an area of my page; then when the image is clicked, I show the image in its actual large size.

  48. Theo says:

    Fantastic point on the "width:remainder" parameter. How could they miss it!

  49. Moiz Raja says:

    Very well explained.

  50. Forkoff says:

    One thing that gets caught our by this is iFrames. The only fix I found is to wrap my iFrame in another DIV and put my margins on that, then set the iFrame to 100%. Dirty but it works, and yes, I know iFrames are dirty, but I’m o9nly using them for simple time-saver apps for use within the company and never use iFrames in work for our clients unless absolutely necessary!

  51. Sidney says:

    Good stuff man keep up the good work.

  52. khrao says:

    I am very impressed and learn more from this article

    Thanks,

  53. Daniel says:

    I came up with an error i suppose. When i do width:auto; it won’t fit 100% like there’s a padding around it. I find this frustrating though, please comment and help me!

    • “width: auto” doesn’t really do anything, it just says “compute the value automatically based on the browser’s default for that element”.

      This article is actually a little out of date now. The correct thing to do now would be to add “box-sizing: border-box” to the element, and then do “width: 100%”. This will ensure that the width doesn’t expand past what you desire, because the 100% width will not include the borders and padding.

      • Stephen Brooks says:

        Seems slightly late to the party but, I have come across a related issue a few times now and the solution seems to be to either use a table, or the table display option for the parent, and table-cell for the child elements in later browsers.

        The issue is when you have a parent div set to 100% because you want it to dynamically stretch with the page, within which there are two spans/divs which are inline-block elements. The first has a fixed width and the second will desirably fill the ‘remaining’ space.

        The problems are :
        – 100% takes the length of the parent and applies this, so the second element overflows.
        – auto, makes the second element only as long as necessary for it’s contents.

        Logically I’d expect here 100% would respect the bounds of the parent element?

        
        #a {
            display :table;
        }
        
        #b1 {
            display: table-cell;
            width: 20px;
        }
        
        #b2 {
            display: table-cell;
            width : 100%;
        }
        
        <div id="a">
            <span id="b1">Fixed</span>
            <span id="b2">Remaining</span>
        </div>
        
        
  54. I have a question my partner and I developed a website but in mid-stream my partner bailed out. I tried to finish it myself and it didn’t work out. It does not re-size properly. I looking for another partner but I’m hoping to fix the problem. Maybe you could look at the CSS part of it and let me know what I’m doing wrong.

  55. martin says:

    It was very refreshing to also visualize this. I noticed if also used a – float:left ; clear:left – in the div where we put – margin:auto – for example, it will clear out the margin auto and shrinks back to minimal width? Not really understand why…

    • That’s because you can’t center an element that’s floated. If it’s floated, that means it gets pushed to the left as far as it can go, so the float will supersede auto margins.

  56. Nice tip, I’m keep my eyes peeled from now.

  57. Ayesha says:

    Refreshing. As my images and layout blocks are looking great now.

  58. Laquack says:

    Thank you for taking the time and writing this great post ^^

  59. emirjon says:

    #page {
    width: 100%;
    -webkit-box-sizing: border-box;
    -moz-box-sizing: border-box;
    box-sizing: border-box;
    }
    will fill the parent margins

    This is a CSS3 solution

  60. chaco says:

    yes,i quite agree with you,but there seem is a special case. I give the ‘div’ a width of 100% which parent is a ‘ li ‘ with a width of 25%, and it works. The div’s content area exactly equal to the width of its parent

  61. Ian Jennings says:

    I’ve written an in depth post about this issue with code examples and diagrams on my blog.

  62. Thank you for taking the time and writing this great post

  63. Xem phim says:

    It really helped me to understand css widths better.

  64. I used my web sites footer image but not but it was filling picture page, wher is problem I dont understand.Can you help me please? this is my site: http://www.arabaoyunlari04.com

  65. Yuriy Gagarin says:

    It’s true if parent element is smaller than window size. If window is smaller than element, 100% means 100% of window not parent element.

  66. Akshay Joshi says:

    That’s an informative article but may I know how to fit and scale images inside div properly. A site where I need help is http://www.ajostore.com. Please I await your answer.

  67. Monir says:

    My “div” width:1500px, can i use width 100% for this ? ….. (width:100%= how pixel??), i am not clear about it. please help me, thanks.

    • No, that’s not the same thing.

      Most of the time, you don’t need to do “width: 100%”. If you want something 1500px, then just set it to 1500px. But if you want it to fit the whole screen, then don’t set the width at all. It will naturally fill the space. If the parent element is 1500px, then 100% will be equal to 1500px. But you don’t need “100%”, because it will do it naturally, on its own. All divs will expand naturally to fit their parent (or fit the screen, if there is no parent element).

  68. Edson says:

    This really did clear somethings for me, thanks!

  69. phim s says:

    then don’t set the width at all. It will naturally fill the space

  70. alma says:

    If you have a “small table” an want to be more readable you need this option, you can use width:50%-60%

  71. Jane Brewer says:

    Thanks for sharing as I was wondering for this and got it from here

  72. BatsHub says:

    Actually few of our teammates at BatsHub did. I liked this

    “What do you think? Have you ever misinterpreted percentage widths, and abandoned using them because they didn’t work as you expected?”

    Will share it with them :)

  73. Jim Fuhrman says:

    I’m glad I’m not alone with the frustration of using width: 100% and height: 100%. I’m having a problem with them right now as I speak.

  74. William says:

    Great to see a good information. On my webpage the trick worked.

  75. Benur21 says:

    I wonder what happens under the hood when I define a div’s width/height to be the same as its div child (eg: fit-content, height default, …) and its div child’s width/height to be the same as its parent at the same time. In my browser they end up both at 0.

  76. Steffie says:

    It’s the secret sauce for responsive design! With a width: of 100%, your content adapts beautifully to any screen size.

    Thanks for Sharing!

Leave a Reply

Comment Rules: Please use a real name or alias. Keywords are not allowed in the "name" field and deep URLs are not allowed in the "Website" field. If you use keywords or deep URLs, your comment or URL will be removed. No foul language, please. Thank you for cooperating.

Markdown in use! Use `backticks` for inline code snippets and triple backticks at start and end for code blocks. You can also indent a code block four spaces. And no need to escape HTML, just type it correctly but make sure it's inside code delimeters (backticks or triple backticks).