1

I have a responsive layout with 2 colums (main & sidebar). The side bar has a fixed width and the main column's width is responsive. do to the sidebar being a fixed width, I can't set the main column to 100% without the sidebar dropping down obviously. Is there any way to let javascript calculate the width of the main column depending on browser size? (taking into account the fixed width column that should be next to it)

#main {
	background-color: #0F0;
	float: left;
	height: 400px;
	width: 100%;
}
#sidebar {
	background-color: #C60;
	float: right;
	height: 400px;
	width: 300px;
}
<div id="main">
</div>

<div id="sidebar">
</div>

0

1 Answer 1

2

This is possible using CSS's calc() function.

#main {
  background-color: #0F0;
  float: left;
  height: 400px;
  width: calc(100% - 300px);
}
#sidebar {
  background-color: #C60;
  float: right;
  height: 400px;
  width: 300px;
}
body {
  margin: 0;
}
<div id="main">
</div>
<div id="sidebar">
</div>


If you really want to use JavaScript you need set main's width equal to the window's width without scrollbar (document.body.clientWidth) minus sidebar's width.

Also, the function doMath() needs to be executed when the window is resized.

var main = document.getElementById('main');
var sidebar = document.getElementById('sidebar');

function doMath() {
  main.style.width = document.body.clientWidth - sidebar.offsetWidth + 'px';
}

doMath();
window.onresize = doMath;
#main {
  background-color: #0F0;
  float: left;
  height: 400px;
  width: 100%;
}
#sidebar {
  background-color: #C60;
  float: right;
  height: 400px;
  width: 300px;
}
body {
  margin: 0;
}
<div id="main">
</div>
<div id="sidebar">
</div>

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.