Make Div as wide as it needs to be

后端 未结 5 578
我在风中等你
我在风中等你 2021-01-01 21:47

To explain my problem, I\'m trying to make a div wide enough to accommodate a dynamically generated title without wrapping it, but the div also has other content, which I wa

相关标签:
5条回答
  • 2021-01-01 22:10

    For headlines you should use the <hN> tags (<h1>, <h2> etc).

    For no text wrap:

    white-space: nowrap;
    

    On the element who's text you don't want to wrap.

    Working Example on jsFiddle

    0 讨论(0)
  • 2021-01-01 22:23

    Block elements such as divs extend as far as content pushes them, unless specified by explicit widths or heights.

    A pure CSS solution for this is unlikely without setting a max-width on the div.

    A pointer on CSS:

    • Don't include the tags in your selectors (i.e. tag.class) as you are then forced to use that tag with that class. Simply using .class will make it easier to change your markup (should you need to) as well as make your class extend its use to more than a single tag.
    0 讨论(0)
  • 2021-01-01 22:33

    If i understand your correctly you can easily set the same width for yours text as for yours title using JS or jQuery, for ex:

    $('.text').width($('.title').width())
    

    and run it at jQuery(document).ready or by event if you add it dynamically

    0 讨论(0)
  • 2021-01-01 22:34

    Is this (jsFiddle) what you're trying to accomplish?

    I just added display: table; to .box's CSS. This expands the main div to the width of the title span but wraps the text span.

    Note: You can also set a constant width to prevent the div from expanding to the width of the window. This way it will still expand to the width of the title if it is larger than your constant width, but will not grow if the user drags out the window. In my example I added width: 100px; to demonstrate.

    0 讨论(0)
  • 2021-01-01 22:37

    A working jQuery example:

    http://jsfiddle.net/8AFcv/

    $(function() {
        $(".box").width($(".title").width());
    })
    
    0 讨论(0)
提交回复
热议问题