Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Set min-width to width of contents

Tags:

css

responsive

I have a div with a background that contains a table. I want the div to have 100% width, except when that is narrower than the table is long. I can do something like this:

.my-div {
  width:100%;
  min-width:900px;
}

That's great for a table that is 900px wide, but if it is narrower than that, I will have unwanted scrollbars and if it is wider than that, I will have content that is unreachable. Obviously, this can trivially be solved with JavaScript, but I want to know if there is a CSS-only solution, so my application isn't so JS-heavy.

For a visual of what's happening, see here. What I want is for the green background to overflow the viewport when the text in the table does.

like image 864
Joshua Clark Avatar asked Jul 21 '12 18:07

Joshua Clark


People also ask

Does Min width override width?

The min-width property in CSS is used to set the minimum width of a specified element. The min-width property always overrides the width property whether followed before or after width in your declaration. Authors may use any of the length values as long as they are a positive value.

What is width min-content?

The min-content keyword value. According to the W3C specifications, the min-content is the smallest size a box can take without overflowing its content. For horizontal content, the min-content uses the length of the widest bit of content in the element box and automatically sets that length value as the box width.

Can we set min width and max width for an element at the same time?

And min-width specify lower bound for width. So the width of the element will vary from min-width to ... (it will depend on other style). So if you specify min-width and max-width , you will set up a lower and upper bound and if both are equal it will be the same as simply specifing a width .


1 Answers

If I understand your problem correctly, this should help:

.my-div {
  /*width:100%;*/
  height:400px;
  background-color:#bada55;
  display: inline-block; // this is the key
}

Your example modified here: http://jsfiddle.net/nvLnodLh/

like image 91
Tamas Szoke Avatar answered Sep 29 '22 13:09

Tamas Szoke