user2208349
user2208349

Reputation: 7709

css how to make the div width just for the content

I have this html:

<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
    <title>Test Float</title>
    <link rel="stylesheet" href="Styles/style.css" />
</head>
<body>
    <div class="header">
    </div>
    <div class="mainContent">
        <div class="slideBar"></div>
        <div class="content">
            up
            <div class="div1">
                Hello
            </div>
            down
        </div>
    </div>
    <div class="footer"></div>
</body>
</html>

And this is my css style:

html, body {
margin:0px;
height:100%;
}
.header {
    width:100%;
    height:20%;
    background-color:red;
    border-radius:10px;
}
.footer {
    width:100%;
    height:20%;
    background-color:green;
}
.mainContent {
    width:100%;
    height:60%;
}
.slideBar {
    width:20%;
    height:100%;
    float:left;
    background-color:blue;
}
.content {
    width:80%;
    height:100%;
    float:right;
    background-color:yellow;
}
    .content .div1 {
        border:2px solid black;
        margin-left:10px;
    }

This is the result: enter image description here

My problem

the border of the hello word goes to all the width. but I need it just to be surround the text

Upvotes: 1

Views: 513

Answers (4)

i.nata
i.nata

Reputation: 11

You can write display: inline-block; for div with class = div1 or replace your div to span. Div is block element on default. If you use a text it is better to use span - default inline element.

Upvotes: 1

Simon L
Simon L

Reputation: 36

Add display: inline-block to it. http://jsfiddle.net/zhF4f/

Divs are "block elements"(display:block) which mean they take up 100% of their parent width. By setting inline-block, it only wraps the content.

Upvotes: 1

Rose Kunkel
Rose Kunkel

Reputation: 3268

<div> is a block-level element, so in order to get it to shrink around its content, you need to make it act like an inline element. Setting display: inline-block; on .content .div1 will make it behave more or less like an inline element, and so it will fit to contents. See example here: http://jsfiddle.net/6wZhe/

However, what you might want to do is change out your <div> tag for a <span> tag, which is another multipurpose non-semantic container, except that is is an inline element, not a block-level element.

If you still want the linebreak after the <div> you can add a <br /> element, or do it with floats.

Upvotes: 4

CodeVirtuoso
CodeVirtuoso

Reputation: 6448

Add display:inline-block; to .content .div1 and in html add a <br> above and below it:

http://jsfiddle.net/LYvft/2/

Upvotes: 1

Related Questions