Welcome to the Treehouse Community
Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.
Looking to learn something new?
Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.
Start your free trial
Nicholas Olsen
Front End Web Development Techdegree Student 19,342 PointsHow can I make my divs grow wider according to their content?
A typical problem I run into is I have a div with an arbitrary amount of text in it. I'd like the text to be centered, but I don't want to define the exact width of the div. Here is an example:
<div>Some arbitrarily long text</div>
div {
margin: 0 auto;
}
In this case, the margin property doesn't do anything because the div is taking up 100% of the available space. This means the text itself is not centered and is instead all the way to the left. I can center the text by setting a fixed width to the div, but I don't want to do that. Instead, I would like to div to grow as the text becomes longer.
Any ideas?
2 Answers
Misha Shaposhnikov
8,718 PointsWhy not put all the text into a paragraph element, and then, in CSS for that element, declare
/*html*/
<div id="my-div">
<p id = "my-p">
Some arbitrary long text
</p>
</div>
/*CSS*/
#my-div{
/*Make any re-sizing changes or other CSS rules*/
}
#my-p{
text-align: center;
}
This way, if you wanted to, you could nest the paragraph element into a div; then, assign an id to that div and manipulate it's width according to your needs while the text inside the div will always be centered since it is inside a paragraph element. Hope this helps. =)
Happy Coding!
Dane Parchment
Treehouse Moderator 11,077 PointsLuckily this is very simple to accomplish. All you need to do is make the height of the text's containing element auto, an example:
I added the box-sizing property and set it to border box so that the padding is calculated into the width and height of the element. The colors is just for easy viewing. So place this into your div and try it out for yourself.
In my opinion this is an easier way to accomplish your goal because all you need to do is add a bit of padding and simply set the height to auto. Hope this helps.
div {
-moz-box-sizing: border-box;
-webkit-box-sizing: border-box;
box-sizing: border-box;
width: 100%;
height: auto;
padding: 1%;
background: slateGray;
color: lavender;
text-align: center;
}
Nicholas Olsen
Front End Web Development Techdegree Student 19,342 PointsNicholas Olsen
Front End Web Development Techdegree Student 19,342 PointsYes, you're right!