Reputation: 4783
I am trying to change the CSS below so that I don't need the JavaScript snippet to achieve the same desired effect.
The JavaScript:
<script>
$(function() {
var pageCount = 2;
var pageWidth = 450;
$("#pages").css('width', window.innerWidth * pageCount);
$(".page").css('margin-right', window.innerWidth - pageWidth);
});
</script>
The HTML:
<!DOCTYPE html>
<html>
<head>
<title></title>
<style>
#pages {
position: absolute;
top: 50%;
height: 200px;
width: 30000px;
margin-top: -100px;
left: 50%;
}
.page {
margin-left: -150px;
width: 300px;
background: blue;
float: left;
}
</style>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script>
</head>
<body>
<div id="pages">
<div class="page">
<h1>Page 1</h1>
<p>This is the first page</p>
</div>
<div class="page">
<h1>Page 2</h1>
<p>This is the second page</p>
</div>
<div class="page">
<h1>Page 3</h1>
<p>This is the third page</p>
</div>
</div>
</body>
</html>
Is there any way I can remove this JavaScript and do the same thing in CSS only? Originally I tried playing around with margin-right: 100%
but couldn't get it to work.
Code Pen: http://codepen.io/anon/pen/gfxeh
Upvotes: 0
Views: 397
Reputation: 982
Yes. You can use the following CSS:
.page {
counter-increment:section;
margin-left: -150px;
width: 300px;
background: blue;
float: left;
margin-right: calc(100%/3 - 300px);
}
#pages {
position: absolute;
top: 50%;
height: 200px;
margin-top: -100px;
left: 50%;
width: calc(100%*3);
}
Upvotes: 1
Reputation: 15430
Alternative solution that works with any number of pages and compatible with older browsers (calc is a new CSS feature)
There is however a limitation: the scroll bar is in the pages element. (there is a way to work around this which I will show bellow)
HTML
<div id="pages">
<div class="page">
<div class="content">
<h1>Page 1</h1>
<p>This is the first page</p>
</div>
</div>
<div class="page">
<div class="content">
<h1>Page 2</h1>
<p>This is the second page</p>
</div>
</div>
<div class="page">
<div class="content">
<h1>Page 3</h1>
<p>This is the third page</p>
</div>
</div>
</div>
CSS
#pages {
width: 100%;
overflow-x: scroll;
white-space: nowrap;
}
.page {
width: 100%;
display: inline-block;
}
.page > .content {
width: 300px;
background: blue;
margin: 0 auto;
}
If your page will only contain the carousel, you can replace #pages
with body
so that the scroll bar is the main scrollbar
By the way, the CSS in the marked solution is not working. It should be
.page {
...
margin-right: calc(100%/3 - 300px);
}
Upvotes: 0