Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

CSS: Is it correct that text content of a div overflows into the padding?

I expected that the padding inside a div would remain clear of any text. But given the following html/css, the content-text spills out into the padding;

<div class="foo">helloworld</div>  .foo {   float: left;   overflow: hidden;   background: red;   padding-right: 10px;   width: 50px;   border: 1px solid green; } 

The text overflows it's 50px size and into the 10px padding. Is that by design? If so it seems pretty dumb - padding isn't padding if it's got stuff in it! Or am I just doing something wrong?

Regards, CSS newbie.

like image 489
Nigel Alderton Avatar asked Nov 25 '10 16:11

Nigel Alderton


People also ask

Why is content overflowing the div?

Overflow happens when there is too much content to fit in a box. CSS provides various tools to manage overflow. As you go further with CSS layout and writing CSS, you will encounter more overflow situations.

How do you handle text-overflow in CSS?

A text-overflow property in CSS is used to specify that some text has overflown and hidden from view. The white-space property must be set to nowrap and the overflow property must be set to hidden. The overflowing content can be clipped, display an ellipsis ('…'), or display a custom string.


1 Answers

This is the correct behavior. overflow: hidden will clip content that extends outside the box. Padding is inside the box, so content will happily overflow into that space if necessary.

CSS Box model
(source)

To get the effect you seem to be aiming for, one solution is wrap your div.foo in an another div and set the background on that one instead, like this:

<div class="foowrapper">     <div class="foo">purrrrrrrrr</div> </div>  .foo {     overflow: hidden;     width: 40px; } .foowrapper {     padding-right: 10px     background: red;     border: 1px solid green; } 
like image 168
Brant Bobby Avatar answered Sep 28 '22 06:09

Brant Bobby