Tyler
Tyler

Reputation: 322

Give parent the same width as child

(Note: For compatibility reasons I may only use HTML and CSS for this.)

I have a div containing an h4 tag. What ends up happening is my h4 tag has a auto-defined width based on how much text is included. However when I include it under my div tag the div automatically uses width:100% instead of surrounding the tag like I want it to. This becomes a problem because when I change the color of the div via hover I see a ton of extra unfilled space.

Here is one example of the issue I'm experiencing:

<a href='./HH.html'>
<div id='homenav'>
    <h4>
        HH
    </h4>
</div>
</a>

This is my current CSS:

h4{padding:0px;Margin:5px;}
#homenav
{
   font-family: "Lucida Sans Unicode", "Lucida Grande", Sans-Serif;
   background: #e8edff;
   color: #669;
   text-align:center;
   vertical-align: middle;
   display:-webkit-box;
   -webkit-box-pack:left;
   -webkit-box-align:left;
   display:-moz-box;
   -moz-box-pack:left;
   -moz-box-align:left;
   border-radius: 5px;
   padding: 2px;
   width:auto;  
}

#homenav:hover
{
   background:#D0DAFD;
   color:#333399;
}

Upvotes: 0

Views: 137

Answers (3)

Tomas
Tomas

Reputation: 59575

You can use display: table. See your example modified: http://jsfiddle.net/cArg7/1/

h4{padding:0px;Margin:5px;}
#homenav
{
font-family: "Lucida Sans Unicode", "Lucida Grande", Sans-Serif;
background: #e8edff;
color: #669;
text-align:center;
vertical-align: middle;
border-radius: 5px;
padding: 2px;
width:auto; 
display: table;
}

#homenav:hover
{
background:#D0DAFD;
color:#333399;
}

And simplify the html code, merge <a> and <div> tags:

<a href='./HH.html' id='homenav'>
    <h4>
        HH
    </h4>
</a>

Upvotes: 1

Csarsam
Csarsam

Reputation: 416

Setting the display of the parent div to inline-block will wrap the parent div to the width of the text. See this as an example.

Upvotes: 0

user2445124
user2445124

Reputation:

You can add display: inline-block to the parent div and remove the width attribute.

Example:

HTML:
<div class="container">
    <h2>Text</h2>
</div>

CSS:
.container {
    display: inline-block;
}

Demo: http://jsfiddle.net/5qPH9/

Upvotes: 1

Related Questions