Search code examples
csscenteringalignment

Make div size as per contents and horizontally center inside it's parent


I have a div message which basically has a text and a link. I want its size to be changing based on the string inside it. Also I want this message div to be centered inside its container.

I have been playing with it for a while without much luck. Here is the link to JSfiddle: http://jsfiddle.net/pDYJ8/

Also I don't know how make that text and link appear one after other ( not on the new line )

Here is the code:

<div class="container">
<div class="message">
    <p>do you want to </p> 
    <a href="somewhere" target="_blank">
        buy this product
    </a>
</div>
</div>
.container {
    position: absolute;
    background: #666;
    top:25%;
    width:100%;
    font-size: 15px;
    color: #e47911;
}
.message {
    margin-right: auto;
    margin-left: auto;
    background: #ddd;


    width:100px;   
}

Tried display inline block to fit its content but then it wouldn't center it inside its parent.

Keeping width 100px for now just to mock my requirements


Solution

  • Just Tweak Some CSS

    See the demo fiddle.

    .container {
        position: absolute;
        background: #666;
        top:25%;
        width:100%;
        font-size: 15px;
        color: #e47911;
        text-align: center; /*added*/
    }
    .container .message {
        display: inline-block; /*added*/
        text-align: left; /*added*/
        background: #ddd;
    }
    
    .message p { /*added*/
        display: inline-block;
    }
    

    Explanation

    The text-align center causes the now inline-block display of .message to center, which is then reset to have its own text-align back at left (this is not necessary). To get the a on the same line, the p also needs to be some type of inline display, here I chose inline-block as well..