Set height of <li> based of div height - html

hope you can help me.
I am trying to create a navigation with a variable amount of list elements. Now I want to automatically set the height of the list elements based on the height of the surrounding div element, and the number of list elements that are in the div. Is there a way to do so, or can I only do it the other way around, by simply not giving the div a height value, but rather give the list elements a fixed height?
Hope you can help me.
#nav ul{
margin: 0;
padding: 0;
list-style: none;
}
#nav{
margin-top: 30px;
width: 19%;
background-color: red;
float:left;
border-top: 1px solid black;
}
#nav ul li{
text-align: center;
width: 100%;
background-color: yellow;
height: 50px;
margin-top: 20px;
line-height: 50px;
border-bottom: 1px solid black;
border-left: 1px solid black;
transform: rotate(20deg);
}

You can use the below code,it will definitely work
<!DOCTYPE html>
<html>
<head>
<meta charset="ISO-8859-1">
<title>Insert title here</title>
</head>
<body>
<div id="change" style="height:200px;border:1px solid black">
<ul>
<li>HI</li>
<li>Hello</li>
<li>Bye</li>
<li>Byesdfsd</li>
<li>sdfsd</li>
<li>sdfsd</li>
</ul>
</div>
<script>
var height=document.getElementById("change").style.height;
height=height.replace("px","");
var lis=document.getElementsByTagName("li");
for(var i=0;i<lis.length;i++){
lis[i].style.height=(parseInt(height))/(parseInt(lis.length))+"px";
console.log("getting height "+lis[i].style.height);
}
</script>
</body>
</html>
So you can give the height of the div in a class or in the inline style,but you will have to change the code accordingly in the js part for fetching the height of the div.
I have got the li tags and then depending on their number i have divided the height of the enclosing div by the number of list tags

So basically what you want is that if the div is 100px high and you have 4 items in the list, each item should be 25px high, and if you have 5 items then each should be 20px high. Is it correct?
In this case, if you don't want to resort to javascript, you can use flexbox.
Here, javascript is only used to dinamically add items to the menu in order to demonstrate flexbox behavior:
var menuEl = document.getElementById('menu');
document.getElementById('addMenuItemBtn').onclick = function () {
var numberOfItems = menuEl.childElementCount;
// create a new menu item
var newListElement = document.createElement('li');
newListElement.appendChild(document.createTextNode('Menu item ' + (numberOfItems + 1)));
newListElement.setAttribute('class', 'item');
// append the new item
menuEl.appendChild(newListElement);
}
document.getElementById('removeMenuItemBtn').onclick = function () {
var numberOfItems = menuEl.childElementCount;
if (numberOfItems > 1) {
// if there are at least 2 items, remove the last item
var lastItemIndex = numberOfItems - 1;
var lastItem = menuEl.children[lastItemIndex];
lastItem.remove();
}
}
.container {
list-style: none;
margin: 0;
padding: 0;
width: 320px;
height: 240px; /* enough for 6 items with a height of 40px */
background-color: #DDD;
display: flex;
flex-direction: column;
}
.item {
width: 100%;
margin: 5px;
padding: 5px;
flex-grow: 1;
flex-shrink: 1;
flex-basis: 30px;
}
<ul class="container" id="menu">
<li class="item">Menu item 1</li>
<li class="item">Menu item 2</li>
</ul>
<input type="button" value="Add menu item" id="addMenuItemBtn">
<input type="button" value="Remove menu item" id="removeMenuItemBtn">
Since the container is 240px high and items have a minimum height of 40px (flex-basis: 30px + margin: 5px), there is enough space for 6 items. If you add more than 6 items, the extra elements will overflow.
You can read more about flexbox in this article on css-tricks.com.
You'll likely want to change a lot of things in my snippet, it's just a proof of concept!
Just keep in mind that some old browsers don't support it, or support it with
a legacy syntax.

Related

Decrease padding size as parent element getting smaller

I have a grid that draws squares in cells. It has number of rows and number of columns, then it draw the grid cells and check if in each cell there should be a square or not (according to an array) and draws a square if needed.
The HTML end result looks something like this: (lets say I have 1 row and 3 columns and only 2 cells should have squars)
.row {
display: flex;
flex-wrap: wrap;
flex: 10000 1 0%;
}
.column {
display: flex;
flex-wrap: wrap;
max-width: 100px;
min-width: 10px;
padding: 4px;
border: 1px solid grey;
}
.square {
background-color: red;
width: 100%;
aspect-ratio: 1/1;
border-radius: 5px;
}
<div class="row">
<div class="column">
<div class="square"></div>
</div>
<div class="column">
<div class="square"></div>
</div>
<div class="column"></div>
</div>
The rows take the full width of the screen and the size of the columns should be identical between all of the columns and changing by the number of columns on the screen (For example if I have 5 columns they should all be with a width of 100px, but if I have 1000 columns they should all be with a width of 10px).
My problem is that after a certain break point in the column size the padding and border radius seems weird and I want to change their values when I hit that break point.
I can't use #container queries as there are still not fully supported.
If it help I'm using vue 2. but I think a CSS solution will be better in this case.
Trying to address the issue described:
My problem is that after a certain break point in the column size the
padding and border radius seems weird and I want to change their
values when I hit that break point. I can't use #container queries as
there are still not fully supported.
I crafted a little demo that helped me better explore the conditions bringing to such a scenario.
Obtaining border: collapse equivalent on flexbox items
The .row element remains a flexbox container but its flex items instead of having their border set, they are styled with their outline set.
The outline doesn't occupy space and it's expected to "collapse" when colliding with the outline produced by another element.
So to make it sure the layout wasn't affected by styling oddities, in the attempt to show off the borders of the flex items, this demo just relies on 2 key aspects to render those borders:
Setting the gap between the flex items
Setting the outline size expected to cover the gap left between
elements
.row {
gap: var(--col-gap);
}
.column {
outline: var(--col-gap) solid gray;
}
Using ::after for adding content to an element
Plus the red dot is applied as an ::after pseudo element with position:absolute, again to make sure that nothing affected the grid layout:
.column.square::after {
position: absolute;
content: '';
background-color: red;
width: 50%;
aspect-ratio: 1/1;
border-radius: 100%;
top: 50%;
left: 50%;
transform: translate(-50%, -50%);
}
The dashboard - exploring the options
Starting from there I added a "dashboard" with position: fixed that remains on top of the page and lets you control:
column width (px): here you set the width changing the cols per row according to the available container space
columns per row: here you set the cols per row changing their width according to the available container space
width
gap between cells (px): the gap between cells on the grid
toggle red dots visibility: will show/hide the red dots proving again that display: none; doesn't change the grid layout that it's depending exclusively by the .column element size set through the custom variable --col-width
toggle counter visibility: will show/hide the counter on top of each flex item
Conclusions so far:
Despite the efforts to minimize any interfence and taking all the steps needed to correctly setup a grid layout depending only on the fixed size of its cells, there are still some rendering issue with sometimes the occurrence of regular mismatching patterns on the border size for some lines. I should say that I only experience the problem on my laptop display and not on my desktop monitor so that's another factor.
I tried with different parameters on my demo and playing with the numbers, considering also the gap. A good and safe layout can be found minimizing potential problems (also raising the border size for example).
I couldn't get further than this using the flex layout.
const container = document.getElementById('container');
//draws the board
emptyElementAndFillWithColumns(container, 100);
//sets some columns randomly as .square
addRandomSquares(container);
//initializes the dashboard with the value coming from the css custom props
let columnsGap = parseInt(getCssCustomProp('col-gap'));
let columnsWidth = parseInt(getCssCustomProp('col-width'));
document.getElementById('gap').value = columnsGap;
document.getElementById('width').value = columnsWidth;
document.getElementById('width').dispatchEvent(new Event('change'));
document.getElementById('cols').value = Math.trunc(container.offsetWidth / (columnsWidth+columnsGap));
//input#width change event handler
document.getElementById('width')
.addEventListener('change', event => {
const width = parseInt(event.target.value);
const newCols = Math.trunc(container.offsetWidth / (width+columnsGap));
setCssCustomProp(container, 'col-width', `${width}px`);
document.getElementById('cols').value = newCols;
});
//input#cols change event handler
document.getElementById('cols')
.addEventListener('change', event => {
const cols = parseInt(event.target.value);
const newWidth = Math.trunc(container.offsetWidth / cols) - columnsGap;
setCssCustomProp(container, 'col-width', `${newWidth}px`);
document.getElementById('width').value = newWidth;
});
//input#gap change event handler
document.getElementById('gap')
.addEventListener('change', event => {
const gap = parseInt(event.target.value);
setCssCustomProp(container, 'col-gap', `${gap}px`);
columnsGap = gap;
});
//input#toggle-dots change event handler
document.getElementById('toggle-dots')
.addEventListener('change', event => {
container.classList.toggle('hide-dots');
});
//input#toggle-counters change event handler
document.getElementById('toggle-counters')
.addEventListener('change', event => {
container.classList.toggle('hide-counters');
});
//sets the --propName custom property at the style of target
function setCssCustomProp(target, propName, value){
target.style.setProperty(`--${propName}`, `${value}`);
}
//gets the --propName custom property value from the rule set on :root
function getCssCustomProp(propName){
const propValue =
getComputedStyle(document.documentElement).getPropertyValue(`--${propName}`);
return propValue;
}
//resets the container and appends a count number of columns
function emptyElementAndFillWithColumns(target, count){
for (i = 0; i <= count; i++) {
const column = document.createElement('div');
column.classList.add('column');
target.append(column);
}
}
//adds the square class to random .column elements in target
function addRandomSquares(target){
target.querySelectorAll('.column').forEach(column => {
if (Math.random() >= 0.5)
column.classList.add('square');
})
}
:root {
--col-width: 100px;
--col-gap: 1px;
}
*,
*::after,
*::before {
box-sizing: border-box;
margin: 0;
padding: 0;
}
body {
font-family: sans-serif;
}
.row {
display: flex;
flex-wrap: wrap;
gap: var(--col-gap);
counter-reset: itemnr;
}
.column {
position: relative;
display: flex;
flex-wrap: wrap;
width: var(--col-width);
height: var(--col-width);
padding: 4px;
outline: var(--col-gap) solid gray;
}
.column.square::after {
position: absolute;
content: '';
background-color: red;
width: 50%;
aspect-ratio: 1/1;
border-radius: 100%;
top: 50%;
left: 50%;
transform: translate(-50%, -50%);
}
.dashboard {
position: fixed;
right: 1rem;
top: 2rem;
border: solid darkgray;
padding: 1em;
z-index: 100;
background: gray;
color: white;
font-weight: 600;
font-size: 1.2rem;
opacity: .9;
}
.dashboard > *{
display: grid;
grid-template-columns: 1fr auto;
width: 100%;
gap: 1em;
}
.dashboard label{
}
.dashboard input[type="number"] {
width: 5em;
cursor: pointer;
}
.dashboard input[type="checkbox"] {
width: 1rem;
line-height: 1rem;
cursor: pointer;
}
#container.hide-dots .square::after{
display: none;
}
#container.hide-counters .column::before{
display: none;
}
small{
grid-column: 1 / -1;
font-size:.8rem;
text-align: center;
width: 100%;
margin-bottom: 1rem;
}
.column::before{
position: absolute;
counter-increment: itemnr;
content: counter(itemnr);
font-size: .8rem;
z-index: 10;
font-weight: 600;
}
<div id="container" class="row">
<div class="column square">
</div>
<div class="column"></div>
</div>
<div class="dashboard">
<div>
<label for="width">column width (px):</label>
<input
id="width" type="number" max="100" min="10">
</div>
<div>
<label for="cols">columns per row:</label>
<input
id="cols" type="number" max="50" min="1">
</div>
<div>
<label for="gap">gap between cells (px):</label>
<input
id="gap" type="number" max="10" min="0">
</div>
<div style="margin-top: 1rem;">
<label for="toggle-dots">toggle red dots visibility:</label>
<input id="toggle-dots" type="checkbox" checked>
</div>
<div>
<label for="toggle-counters">toggle counter visibility:</label>
<input id="toggle-counters" type="checkbox" checked>
</div>
</div>
If you want to increase or decrease size of padding you can give padding size in percent (%) that depends on parent element.

Allow a list of elements to overflow outside the parent div while maintaining the scrollability of parent on y axis

I'm currently working on a list, and it's scrollable on y-axis (overflow-y: scroll). I hope when the mouse hover above the list elements, they will scale up and overflow outside the container. However, as the container is now set to overflow-y: scroll for the scroll bar, it doesn't allow the children elements to overflow. Basically, I hope to have a scroll bar while allowing child elements to overflow out of the box. Please help.
body {
display: flex;
justify-content: center;
align-items: center;
}
ul {
padding: 8px;
border: 1px solid green;
/* overflow-y: scroll; */
height: 300px;
width: 200px;
}
li {
list-style-type: none;
height: 80px;
border: 1px solid brown;
transition: 0.5s;
}
li:hover {
transform: scale(1.3);
}
<body>
<ul>
<li>
Hello
</li>
<li>
Hello
</li>
<li>
Hello
</li>
<li>
Hello
</li>
<li>
Hello
</li>
</ul>
</body>
If I understand correctly your needs, I dont think you can show overflow parts of an element in a hoverflow:scroll container.
I think/am convinced that there is a better way to do this, but I leave my attempt here.
Notes :
It only copy the text of the element, if you have more element, (in line with this attempt) you will probably need to clone (MDN) the hovered element with its children.
Because on top of the scrollbar and my element is outside the container, it's not easy to scroll
let element = document.getElementById("hoveredElement");
showHoveredElement = (li) => {
let offsets = li.getBoundingClientRect();
element.textContent = li.textContent;
element.style.top = offsets.top + window.scrollY +"px";
element.style.left = offsets.left + window.scrollX +"px";
element.style.width = offsets.width+"px";
element.style.height = offsets.height+"px";
element.classList.remove("d-none");
}
hideHoveredElement = () => {
element.classList.add("d-none");
}
document.querySelectorAll("li").forEach((li) => {
li.addEventListener("mouseover", () => {
showHoveredElement(li);
})
li.addEventListener("mouseout", () => {
hideHoveredElement();
})
});
body {
display: flex;
justify-content: center;
align-items: center;
}
ul {
padding: 8px;
border: 1px solid green;
overflow-y: scroll;
overflow-x: hidden;
height: 300px;
width: 200px;
}
li, #hoveredElement {
height: 80px;
border: 1px solid brown;
}
#hoveredElement{
position:absolute;
transition-duration: 0.5s;
background-color:white;
}
#hoveredElement:hover {
display:block;
transform: scale(1.3);
}
.d-none{
display:none;
}
<ul>
<li>
A
</li>
<li>
B
</li>
<li>
C
</li>
<li>
D
</li>
<li>
E
</li>
</ul>
<div id="hoveredElement" class="d-none"></div>

Right items in header-bar not vertically centered. float:right'ed items seem to not inherit *ed properties

I am trying to create the following design
Where the left side is an image followed by a tag with words.
on the right are the menu options which should look like they are clickable. The slashes that separate them should never move change color etc. However "About" "Contact" and "The Future" will eventually look different when hovered over and will take you to different pages on the site.
So when I attempted to create this I made the following HTML and CSS (make sure the window is wide when you run it)
.modernShadow {
box-shadow: 0 2px 5px 0 rgba(0, 0, 0, 0.16), 0 2px 10px 0 rgba(0, 0, 0, 0.12);
}
.fittingObject {
max-width: 100%;
max-height: 100%;
}
#topdiv {
position: fixed;
z-index: 2;
background-color: #4FBEA9;
width: 100%;
height: 44pt;
padding-top: 3pt;
padding-bottom: 3pt;
padding-left: 3pt;
padding-right: 3pt;
}
#topdiv * {
display: inline;
vertical-align: middle;
}
.title {}
.titleLogo {}
.titleHere {
color: white;
}
.rightList {
float:right;
vertical-align: middle;
}
<header>
<!-- Displays in tab bar -->
<title>Logo Here</title>
<div id="topdiv" class="modernShadow">
<img src="https://cdn1.iconfinder.com/data/icons/computer-system-files-essential-glyph/48/Sed-40-512.png" class="fittingObject" />
<h1 class="title">
<h1 class="titleLogo">Logo</h1>
<h1 class="titleHere">Here</h1>
</h1>
<nav class="rightList">
<ul>About</ul>
/
<ul>Contact</ul>
/
<ul>The Future</ul>
</nav>
</div>
</header>
And the result is this
And I can't explain why because I don't understand what is happening to make it this way.
Why are components under float:right not vertically aligned like everything else? I believe #topdiv * gives every subcomponent the style vertical-align: center so why isn't that coming into play?
Where is the spacing between the words and the "/"s coming from?
I am not sure it isn't just a fluke that "Logo Here" is appearing vertically centered... Maybe that is just the font size? But that is set by the .fittingObject css. (the title logo should be as big as it can be)
The end goal is essentially the picture above. The font size of the right items is variable and the text should just always be vertically centered inside of the containing div.
Answers:
Float doesn't work with vertical align, read more about it here; CSS Vertical align does not work with float
UL's have the property padding-inline-start which has a default of 40px and is pushing content to the right.
Max width and Max height properties only specify the limit of a certain element, it doesn't indicate their actual width and height values.
I modified your html to include wrapper divs; classes with left and right. In the right div I placed your rightList which has line-height css property and is an alternative to vertical-align:middle.
.modernShadow {
box-shadow: 0 2px 5px 0 rgba(0, 0, 0, 0.16), 0 2px 10px 0 rgba(0, 0, 0, 0.12);
}
.fittingObject {
max-width: 100%;
max-height: 100%;
}
#topdiv {
position: fixed;
z-index: 2;
background-color: #4FBEA9;
width: 100%;
height: 44pt;
padding-top: 3pt;
padding-bottom: 3pt;
padding-left: 3pt;
padding-right: 3pt;
}
#topdiv * {
display: inline;
vertical-align: middle;
}
.title {}
.titleLogo {}
.titleHere {
color: white;
}
.left,
.right {
width: 49%;
display: inline-block;
}
.rightList {
width:230px;
float: right;
line-height: 60px;
}
.rightList ul {
padding-inline-start: 0px;
}
<header>
<!-- Displays in tab bar -->
<title>Logo Here</title>
<div id="topdiv" class="modernShadow">
<div class="left">
<img src="https://cdn1.iconfinder.com/data/icons/computer-system-files-essential-glyph/48/Sed-40-512.png" class="fittingObject" />
<h1 class="title">
<h1 class="titleLogo">Logo</h1>
<h1 class="titleHere">Here</h1>
</h1>
</div>
<div class="right">
<nav class="rightList">
<ul>About</ul>
/
<ul>Contact</ul>
/
<ul>The Future</ul>
</nav>
</div>
</div>
</header>
do you have any particular reason to use <ul> for all the navs?
if you use
<ul>
<li>About</li> /
<li>Contact</li> /
<li>The Future</li>
</ul>
it will generate the display as you wanted.
the <ul> has default user agent stylesheet.
and for the vertically centered text, if you already set the height for the blocks, you can always use the same statement for line-height (in this case is 44pt) to make it vertically centered.

Align single list item in center CSS

I am creating a navigation bar in Reactjs with four elements. These items are a simple unordered list with some css using flexbox to align them horizontaly.
<ul>
<li>One</li>
<li>Two</li>
<li>Three</li>
<li>Four</li>
<ul/>
What I want to achieve is: When a list item is selected, align the selected list item to center. I have added a professional picture for clarification. This change will later be animated for a smooth transition, like a carousel.
Following is the css for <ul> tag.
ul {
list-style-type: none;
display: flex;
flex-direction: row;
flex-wrap: nowrap;
justify-content: center;
}
What I've tried is to use the align-self: center on the one of the <li> items, but with no luck.
Does anyone have any experience with doing something similar? I am open for all types of solutions, even those that does not use flexbox.
Thank You!
Do the list elements have a fixed with, and do you know how many items there are? If so, you can calculate the center of the list, the item offset, and add a CSS transform.
Example:
You have a list of four items.
Each item has width equal to 100px.
The total width of the list is therefore 400px.
The center point of the list is 200px from the left.
The center point of item number two is 150px from the left. We therefore have to move the list 200px - 150px = 50px from the left.
The center point of item number four is 350px from the left. We therefore have to move the list 200px - 350px = -150px from the left.
If your list is dynamic, both regarding to list length and item width, you can use Element.getBoundingClientRect() to find the elements' dimensions, and use the same calculations as above.
Codepen: https://codepen.io/anon/pen/vjJMVL
HTML:
<ul class="selected-2">
<li>1</li>
<li class="selected">2</li>
<li>3</li>
<li>4</li>
</ul>
<ul class="selected-4">
<li>1</li>
<li>2</li>
<li>3</li>
<li class="selected">4</li>
</ul>
CSS:
ul {
display: flex;
justify-content: center;
list-style: none;
}
li {
width: 80px;
height: 80px;
background-color: #eee;
margin: 10px;
}
.selected {
background-color: #ccc;
}
.selected-2 {
transform: translateX(50px)
}
.selected-4 {
transform: translateX(-150px)
}
Calculate the clicked <MenuItem> center by using Element.getBoundingClientRect() to get it's left, and width, and pass it to the parent (<Menu>). In the parent use the <ul>s ref to get it's left and width with Element.getBoundingClientRect(). Calculate the moveTo state, and update the <ul>s style transform: translateX() accordingly:
const { Component } = React;
const items = ['One', 'Two', 'Three', 'Four'];
class MenuItem extends Component {
clickHandler = (e) => {
const { left, width } = e.target.getBoundingClientRect();
const itemCenter = left + width / 2;
this.props.updateCenter(itemCenter);
}
render() {
const { children } = this.props;
return (
<li onClick={this.clickHandler}>{children}</li>
);
}
}
class Menu extends Component {
state = {
moveTo: 0
};
updateCenter = (itemCenter) => {
const { left, width } = this.ul.getBoundingClientRect();
//this.ul.style.transform = `translateX(${center}px)`;
this.setState(() => ({
moveTo: left + width / 2 - itemCenter
}));
};
render() {
const { items } = this.props;
const { moveTo } = this.state;
return (
<nav>
<ul ref={(ul) => this.ul = ul} style={{
transform: `translateX(${moveTo}px)`
}}>
{
items.map((text) => (
<MenuItem key={text}
updateCenter={this.updateCenter}>
{text}
</MenuItem>
))
}
</ul>
</nav>
);
}
}
ReactDOM.render(
<Menu items={items} />,
demo
);
/** demo only - display the center **/
body::before {
position: absolute;
left: 50%;
height: 100vh;
border-right: 1px solid black;
content: '';
}
nav {
overflow: hidden;
}
ul {
list-style-type: none;
display: flex;
flex-direction: row;
flex-wrap: nowrap;
justify-content: center;
transition: transform 0.5s cubic-bezier(0.175, 0.885, 0.32, 1.275);
}
li {
padding: 1em;
border: 1px solid black;
cursor: pointer;
}
ul li:not(:last-child) {
margin: 0 1em 0 0;
}
<script crossorigin src="https://unpkg.com/react#16/umd/react.development.js"></script>
<script crossorigin src="https://unpkg.com/react-dom#16/umd/react-dom.development.js"></script>
<div id="demo"></div>
Since i don't fully get what you want, this is the best i could have came up with, applying absolute positioning to the selected one and have it overlap the others with z-index
document.querySelectorAll('li').forEach(function(li){
li.addEventListener('click',function(e){
document.querySelectorAll('li').forEach(function(obj){
obj.classList.remove('selected');
});
e.target.classList.add("selected");
});
});
ul {
list-style-type: none;
display: flex;
flex-direction: row;
flex-wrap: nowrap;
justify-content: center;
}
li{
border:1px solid;
padding:10px;
cursor:pointer;
position:relative;
transition:all ease 1s;
margin:0 20px;
}
.selected{
transform:scale(2.1);
background:white;
box-shadow:0px 0px 55px black;
position:absolute;
z-index:5;
}
<ul>
<li>One</li>
<li>Two</li>
<li>Three</li>
<li>Four</li>
</ul>

Full width span floating to right

i wonder how it is possible to have multiple spans inside a div, with the last span floating to the bottom right and taking all the remaining width in the "row".
Here is a fiddle: http://jsfiddle.net/gpakL/
The problem is, that the fullWidth span is not always at the bottom. You can resize your browser window to see the fullWidth span moving.
This is how it should look like:
This is how it shold not look like:
HTML:
<div class="container">
<span class="item">sdfdsfsdf</span>
<span class="item">sdfsdfsdfsdf</span>
<span class="item">dsfdsfdsfsd</span>
<span class="item">fsdfsdfsdffsdf</span>
<span class="item">dsgsdf</span>
<span class="item">dfd</span>
<span class="item">fdfdf</span>
<span class="itemFullWidth">FullWidth</span>
</div>
CSS:
.container {
background-color: blue;
width: 50%;
}
.item {
float: left;
background-color: orange;
height: 30px;
line-height: 30px; /* Vertically center */
margin: 5px;
}
.itemFullWidth {
background-color:green;
display: block;
overflow: hidden;
height: 30px;
line-height: 30px; /* Vertically center */
margin: 5px;
min-width: 80px;
}
If you open to use flexbox, it could be easily done (WebKit demo):
.container {
display: flex;
flex-wrap: wrap; /* allow multiple rows */
}
.container > :last-child {
flex: 1; /* absorb remaining space */
}
check this,
Using position: relative; for the container and position: absolute; for the
.itemFullWidth, you can get it to work to some extent. You'll need some js I guess.
You could consider a JavaScript/jQuery assisted solution for this problem. In a more general case, there are jQuery packages like David DeSandro's Masonry or Packery or Isotope: http://desandro.com/
Here is my version of how you could do this using jQuery.
function resetEndItemWidth() {
var wContainer = $(".container").width();
var minWidthEndItem = parseInt($(".itemFullWidth").css("min-width"));
var endItemMargins = $(".itemFullWidth").outerWidth(true)
- $(".itemFullWidth").outerWidth();
var prevItemOffset = $(".itemFullWidth").prev().offset();
var prevItemWidth = $(".itemFullWidth").prev().outerWidth(true);
var freeWidth = wContainer - (prevItemWidth + prevItemOffset.left);
if (freeWidth < minWidthEndItem) {
newWidth = wContainer - endItemMargins;
} else {
newWidth = Math.max(minWidthEndItem,freeWidth);
}
$(".itemFullWidth").width(newWidth);
}
resetEndItemWidth();
$(window).resize(function(){resetEndItemWidth();});
See the demo at: http://jsfiddle.net/audetwebdesign/m6bx8/
How This Works
I look at the floated sibling before the last item (.itemFullWidth) and determine the amount of free space remaining on the line.
If there is enough free space, I reset the width of the full width item to fill the gap,
otherwise, the full width item is on a separate line and I set it to the width of the parent container.
For full width item (.endItemMargins), you need to account for the left-right margins and you need to get the minimum width from the min-width property.
The min-width requirement could be relaxed if you initialize the original with of the full width item.
Other Comments
The flex box solution is much more elegant. However, it is good to have some options.
Simple jQuery solution, however CSS solutions should be preferred over JS solutions.
http://jsfiddle.net/A8mSu/
HTML:
<div class="container clearfix">
<span class="item">sdfdsfsdf</span>
<span class="item">sdfsdfsdfsdf</span>
<span class="item">dsfdsfdsfsd</span>
<span class="item">fsdfsdfsdffsdf</span>
<span class="item">dsgsdf</span>
<span class="item">dfd</span>
<span class="item">fdfdf</span>
<span class="item itemFullWidth">FullWidth</span>
</div>
JS:
function setWidth()
{
$obj = $('.container .itemFullWidth');
$obj.width('auto').width($obj.parent().width() - $obj.position().left);
}
$(window).resize(setWidth);
$(document).ready(setWidth);
CSS:
.container {
background-color: blue;
width: 50%;
}
.item {
float: left;
background-color: orange;
height: 30px;
line-height: 30px; /* Vertically center */
margin: 5px;
}
.itemFullWidth {
background-color: green;
min-width: 80px;
margin-right: 0;
}
.clearfix:after {
content:"";
display: table;
clear: both;
}
try , Please Checkout http://jsfiddle.net/gpakL/14/
function findWidth (){
var ConWidth = $('.container').width();
var leftWidth = $('.container .item:last').offset().left
var lastItemWidth = $('.container .item:last').width();
var fixPos = ConWidth - (leftWidth + lastItemWidth)
$('.container .itemFullWidth').width( fixPos -20 );
};
$(document).ready(function(){
findWidth();
});
$(window).resize(function(){
findWidth();
});