I would like my div to fit the size of it's content if the size of parent div is smaller than content,
and be the size of parent otherwise.
I can do the 1st by width: fit-content
,
and the 2nd by width: 100%
,
and I wanted to join this together by width: max(100%, fit-content)
,
but seems like this is not working.
Any idea how to do this properly?
CodePudding user response:
You can set the maximum width of an element with max-width
.container{
width:100px;
border:1px solid black;
}
.content{
width:200px;
max-width:100%;
height:20px;
background-color:orange;
}
<div >
<div ></div>
</div>
<br>
<div ></div>
CodePudding user response:
Instead of trying to set the max between 100% and fitting the content, you should instead set the minumum width of the your <div>
to the size of its parent. I was able to reporoduce what you were asking for by setting the container in question (blue box in the example below) to be an inline-block
with min width of 100% under its parent (red box in the example below).
This way, the container always takes 100% of its parent until you resize the parent to be smaller than the inner content, in that case, the container doesn't shrink past the content and so the parent (red box) has to scroll.
This works with the display property as flex
and inline-block
, but not with block
, maybe someone here can explain why.
Here is the example, I made the parent (red box) resizable so you can see the solution in action:
.outer {
width: 500px;
resize: horizontal;
overflow: auto;
border: 5px solid red;
}
.inner {
display: inline-block; /* or flex */
min-width: 100%;
border: 5px solid blue;
box-sizing: border-box;
}
.content {
white-space: nowrap;
background-color: lightGrey;
}
<div >
<div >
<div >For blue box, max is at red box and min is at content</div>
</div>
</div>