CSS: I can't set width to “auto” always appear 100%

后端 未结 7 868
太阳男子
太阳男子 2021-01-28 16:56

for some reason

the width of the div is 100% and if i set it to auto, nothing changes. tried display: block; and still nothing.

what I have in

相关标签:
7条回答
  • 2021-01-28 17:00

    adding to Explosion Pills answer now that its clear what you want, this css should work.

    .box {
        border: 1px solid #555; 
        display: inline-block;        
        float:left;
        clear:both;
    }
    

    Alternatively, you could place some <br> tags after each <div> block

    0 讨论(0)
  • 2021-01-28 17:16

    Setting width:auto; is close to the same as setting width:100%; (the only real difference is that they handle margin and padding differently).

    Also, div objects are by default block elements, so setting display:block; won't change their behavior.


    You said you want the div to take up the width of the words. To do that you can either set display:table-cell (which is not very IE friendly) or you can float the div and it will snap to fit the contents inside.

    .box { float:left; }
    

    Make sure to properly clear your float after the div to avoid breaking the layout of contents below it.

    .clear { clear:both; height:0px; } 
    
    <div class="clear"></div>
    
    0 讨论(0)
  • 2021-01-28 17:17

    Width display: block, the elements will always use as much width as is available. It seems like you want to use display: inline-block

    http://jsfiddle.net/HpMSU/

    0 讨论(0)
  • 2021-01-28 17:18

    width:auto on a DIV expands it to fill it's parent, not to be sized by it's children.

    ex: http://jsfiddle.net/nTWvr/

    To size a DIV by it's content, there are a few methods: How to make div not larger than its contents?

    0 讨论(0)
  • 2021-01-28 17:21

    use display: inline-block

    and add a class

    .clear { clear:both;}

    place it in between the boxes

    so

    http://jsfiddle.net/HpMSU/1/

    0 讨论(0)
  • 2021-01-28 17:22

    I think you want this result:

    <head>
        <title>project x</title>
        <link rel="stylesheet" type="text/css" href="style.css">
    </head>
    <body>
        <span class='box'>This is a box</span>
        <span class='box'>This is another box</span>
    </body>
    
    .box {
        border: 1px solid #555; 
    }
    

    I just changed div to span! try to use proper HTML tags!

    0 讨论(0)
提交回复
热议问题