Using only JavaScript (no jquery) – I want to make it so when a list item has a class of ‘active’ that it be centered inside its container.
The final result will be a carousel where the ‘active’ li will be centered on the page and clicking on another li will make it active and then it will auto center (scroll). The problem I’m having is that I can’t seem to get it to center to start with. The width is 100% of the page so that the width is dynamic.
Any and all help would be great.
html:
<div id="container">
<ul id="carousel">
<li>0</li>
<li>1</li>
<li>2</li>
<li>3</li>
<li class="active">4</li>
<li>5</li>
<li>6</li>
<li>7</li>
<li>8</li>
<li>9</li>
</ul>
</div>
css:
html, body {margin:0;padding:0;height:100%;width:100%;}
ul{
position:relative;
width:100%;
height:322px;
margin:0 auto;
padding:0;
overflow-x:hidden;
white-space: nowrap;
}
li{
position:relative;
display:inline-block;
padding:0;
margin-right:20px;
list-style-type:none;
width:200px;
height:200px;
top: 70px;
background-color:#efefef;
border:1px solid #d3d3d3;
border-radius: 12px;
}
li:first-child {
margin-left: 20px;
}
li.active {
top: 20px;
width:300px;
height:300px;
}
javascript:
var r = document.getElementById('carousel').offsetWidth;
var l = document.getElementById('carousel').scrollWidth;
var m = r / 2;
document.getElementById('carousel').scrollLeft = 0;
document.getElementById('carousel').scrollLeft = m;
You must subtract the half of the width of the active
<li>and the space between the previous<li>fromm