简体   繁体   中英

Make a block level element to have an adjusting width like inline element?

By default, block level elements have width of like 100% even without content, it occupies the space across it's parent element horizontally.

Inline elements on the other hand, adjust it's width depending on it's content. If the the content is long, then the element becomes wider, if the content is short the width shrinks.

在此输入图像描述

Here's a demo .

What I want to achieve here is to make the block-level element to have a width that will adjust depending on it's content like inline element. How will I do that?

Note:

  • I want block elements to be block, not inline-block or inline.
  • I want to avoid floats, I think it can be achieved without floating elements.

I remembered that the width of the table is exactly what I'm trying to mimic. It adjust depending on the length of the content. I found a default stylesheet for HTML 4, the table's display property is set to "table" so I tried it to div and it works:

div{ display:table; background:yellow; }

<div>lorem ipsum dolor</div>

Demo

You can float your block element to left like this

CSS

div { background:yellow; float: left;}

My fiddle

You can simply break your element later or you can use <div style="clear: both;"></div> after your floated div...

My fiddle

Well, I suggest you to add a div or span with display: inline-block INSIDE your main div with display: block . Then use javascript to compute the size of inner element. Then set the width of parent element to the same value.

Anyway, your requirements are very strange

i 'll give littel sample for you

  • HTML
lorem ipsum dolor
lorem ipsum dolorlorem ipsum dolorlorem ipsum dolorlorem ipsum dolor more longger
  • CSS

     div { background:yellow; } span { background:orange; float:left;display:inline; width:auto;padding:0 3px; border-right:1px solid red;} 

element span is float left, and width depend on the content.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM