Box same width as text within

Hi all

I have a jsfiddle here: http://jsfiddle.net/5cEgC/

Simple questions, how can I have the white boxes be the same width as the text like in the example without having to set the width of the white boxes like i have done in the example.

I can do display:inline-block; but then they wrap next to each other.

I need them on top of each other and the white boxes the width of the text within (and the padding)

.box p {float: left;
      clear: left;}

A floated element will “shrink-wrap” its contents, and the clear prevents them lining up against each other.

As Technobear said you can just float the element for a shrink-wrap effect and then make sure following items are cleared but I also see you have tried display:inline-block which will also work except that you will need to add a break after the p element to create the new line so the floated approach is better in this case.:wink:

And if you don’t mind using extra tags in the markup, this is a pretty foolproof method:


<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd">
<html>
<head>
    <meta http-equiv="content-type" content="text/html; charset=utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>template</title>
<!--
http://www.sitepoint.com/forums/showthread.php?1212977-Box-same-width-as-text-within
2014.06.21 10:28
ttmt
-->
    <style type="text/css">
* {
    padding:0;
    margin:0;
}
body {
    background:#bbb;
}
.box {
    max-width:600px;
    margin:50px;
}
p {
    background:white; 
    padding:10px;
    margin:0 0 10px 0;
}
.shorter p {
    display:inline-block;
}
    </style>
</head>
<body>

<div class="box">
    <div class="shorter"><p>The Long Long Long Long Long Long title</p></div>
    <div class="shorter"><p>Shoter text</p></div>
    <p>
        Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.
    </p>  
</div>

</body>
</html>


Thanks Again, I tried float left but completely forgot about clear: left;