I have simple markup like this (a tab menu):
<div class="container">
<div class="tab1"></div>
<div class="tab2"></div>
<div class="tab3"></div>
</div>
That is the case when all elements have an equal width of 33% to fill 100% of the container.
Is it possible to apply a general CSS rule for all containers that automatically detects if, for example, there are only 1 other container or none? And then adjusts the width of the tabs? ("Strech-To-Fit")
Perhaps something with min-width
or max-width
?
The width property is used to fill a div remaining horizontal space using CSS. By setting the width to 100% it takes the whole width available of its parent. Example 1: This example use width property to fill the horizontal space. It set width to 100% to fill it completely.
You can simply use the CSS display property with the value inline-block to make a <div> not larger than its contents (i.e. only expand to as wide as its contents).
One way you can achieve this is setting display: inline-block; on the div . It is by default a block element, which will always fill the width it can fill (unless specifying width of course).
Depending on what browsers you need to support, you may be able to use flexbox:
$('.tab').click(function() { $(this).css('display', 'none'); });
.container { display: flex; } .tab { border: 1px solid black; padding: 5px; flex: 1; margin: 5px; }
<p>Click a tab to remove it</p> <div class="container"> <div class="tab">Tab 1</div> <div class="tab">Tab 2</div> <div class="tab">Tab 3</div> </div> <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
You mean like flexbox?
.container {
display: flex;
height: 50px;
margin-bottom: 1em;
}
[class*="tab"] {
flex: 1;
border: 1px solid red;
}
<div class="container">
<div class="tab1"></div>
</div>
<div class="container">
<div class="tab1"></div>
<div class="tab2"></div>
</div>
<div class="container">
<div class="tab1"></div>
<div class="tab2"></div>
<div class="tab3"></div>
</div>
Or CSS Tables
.container {
display: table;
height: 50px;
width: 100%;
}
[class*="tab"] {
display: table-cell;
border: 1px solid red;
}
<div class="container">
<div class="tab1"></div>
</div>
<div class="container">
<div class="tab1"></div>
<div class="tab2"></div>
</div>
<div class="container">
<div class="tab1"></div>
<div class="tab2"></div>
<div class="tab3"></div>
</div>
You can use display:table
and display:table-cell
see below code
HTML:
<div class="container">
<div class="tab">Tab 1</div>
<div class="tab">Tab 2</div>
<div class="tab">Tab 3</div>
</div>
CSS:
.container {
display: table;
width:100%;
}
.tab {
border: 1px solid black;
padding: 5px;
display: table-cell;
margin: 5px;
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With