Prevent 100vw from creating horizontal scroll - css

If an element is set to width: 100vw; and there is a vertical scrollbar the width of the element will be equal to the viewport plus the width of the scrollbar.
Is it possible to prevent this?
Is it possible to prevent this without disabling horizontal scrolling on the entire page? Aside from changing my css/markup to make the element 100% of the body width I can't think of anything.
Tested in Chrome Version 43.0.2357.81 m & FF 36.0.1 & Opera 20.0.1387.91 on Windows 8.1
Here is the code as requested:
Example
html
<div class="parent">
<div class="box"></div>
</div>
<div class="tall"></div>
css
body { margin: 0; }
html { box-sizing: border-box; }
*, *::before, *::after {
box-sizing: inherit;
position: relative;
}
.parent {
background: rgba(0, 0, 0, .4);
height: 100px;
width: 5rem;
margin-bottom: 25px;
}
.box {
position: absolute;
top: 0;
left: 0;
background: rgba(0, 0, 0, .4);
height: 50px;
width: 100vw;
}
.tall {
height: 100rem;
}

Basically the answer is no, if you have a vertical scrollbar there is no way to make 100vw equal the width of the visible viewport. Here are the solutions that I have found for this issue.
warning: I have not tested these solutions for browser support
tl;dr
If you need an element to be 100% width of the visible viewport(viewport minus scrollbar) you will need to set it to 100% of the body. You can't do it with vw units if there is a vertical scrollbar.
1. Set all ancestor elements to position static
If you make sure that all of .box's ancestors are set to position: static; then set .box to width: 100%; so it will be 100% of the body's width. This is not always possible though. Sometimes you need one of the ancestors to be position: absolute; or position: relative;.
Example
2. Move the element outside of non-static ancestors
If you can't set the ancestor elements to position: static; you will need to move .box outside of them. This will allow you to set the element to 100% of the body width.
Example
3. Remove Vertical Scrollbar
If you don't need vertical scrolling you can just remove the vertical scrollbar by setting the <html> element to overflow-y: hidden;.
Example
4. Remove Horizontal Scrollbar
This does not fix the problem, but may be suitable for some situations.
Setting the <html> element to overflow-y: scroll; overflow-x: hidden; will prevent the horizontal scrollbar from appearing, but the 100vw element will still overflow.
Example
Viewport-Percentage Lengths Spec
The viewport-percentage lengths are relative to the size of the
initial containing block. When the height or width of the initial
containing block is changed, they are scaled accordingly. However,
when the value of overflow on the root element is auto, any scroll
bars are assumed not to exist. Note that the initial containing
block’s size is affected by the presence of scrollbars on the
viewport.
It appears that there is a bug because vw units should only include the scrollbar width when overflow is set to auto on the root element. But I've tried setting the root element to overflow: scroll; and it did not change.
Example

This is a more full-fledged approach to the bug since it still exists in modern browsers. Setting overflow-x: hidden can cause problems or be undesirable in many situations.
A full example is available here: http://codepen.io/bassplayer7/pen/egZKpm
My approach was to determine the width of the scroll bar and use calc() to reduce the 100vw by the amount of the scroll bar. This is a little more complicated because in my case, I was pulling the width of the content out from a box that had a defined with so I needed to declare the margin as well.
A few notes regarding the code below: first, I noticed that 20px seems to be a rather broad magic number for the scroll bars. I use a SCSS variable (it doesn't have to be SCSS) and code outside of #supports as a fallback.
Also, this does not guarantee that there will never be scroll bars. Since it requires Javascript, users that don't have that enabled will see horizontal scroll bars. You could work around that by setting overflow-x: hidden and then adding a class to override it when Javascript runs.
Full SCSS Code:
$scroll-bar: 20px;
:root {
--scroll-bar: 8px;
}
.screen-width {
width: 100vw;
margin: 0 calc(-50vw + 50%);
.has-scrollbar & {
width: calc(100vw - #{$scroll-bar});
margin: 0 calc(-50vw + 50% + #{$scroll-bar / 2});
}
#supports (color: var(--scroll-bar)) {
.has-scrollbar & {
width: calc(100vw - var(--scroll-bar));
margin: 0 calc(-50vw + 50% + (var(--scroll-bar) / 2));
}
}
}
Convert the above to plain CSS just by removing #{$scroll-bar} references and replacing with the px value
Then this Javascript will set the CSS Custom Property:
function handleWindow() {
var body = document.querySelector('body');
if (window.innerWidth > body.clientWidth + 5) {
body.classList.add('has-scrollbar');
body.setAttribute('style', '--scroll-bar: ' + (window.innerWidth - body.clientWidth) + 'px');
} else {
body.classList.remove('has-scrollbar');
}
}
handleWindow();
As a side note, Mac users can test this by going to System Preferences -> General -> Show Scroll Bars = Always

Using max-width attribute with width:100vw and it solved my problem.
Here's what i used.
.full{
height: 100vh;
width: 100vw;
max-width: 100%;
}
Basically what it does is it fixes the max width to the viewport so the horizontal scroll gets eliminated.
More # https://www.w3schools.com/cssref/pr_dim_max-width.asp
The max-width property defines the maximum width of an element.
If the content is larger than the maximum width, it will automatically
change the height of the element.
If the content is smaller than the maximum width, the max-width
property has no effect.

Paddings and borders can interfere. So can margin. Use box-sizing to calculate width including these attributes. And maybe remove margin (if any) from the width.
* {
-webkit-box-sizing: border-box;
-moz-box-sizing: border-box;
box-sizing: border-box;
}
body {
margin: 0; /* interferes with 100vw */
}
.parent {
width: 100vw;
max-width: 100%; /* see below */
}
.box {
width: 100%; /* For those good old-fashioned browsers with no vw or calc() support */
width: -webkit-calc(100vw - [your horizontal margin, if any]);
width: -moz-calc(100vw - [your horizontal margin, if any]);
width: calc(100vw - [your horizontal margin, if any]);
max-width: 100%
}
It seems you have to add max-width: 100%; if there is a reflow which is causing the scrollbar to appear after the initial viewport width calculation. This does not seem to happen in browsers without an interfering scrollbar (iOS, OS X, IE 11 Metro), but can affect all other browsers.

I was also struggling with this, and I also thought of CSS variables as the solution. CSS variables aren't supported in IE11 though so I tried something else:
I fixed it by calculating the width of the scroll bar: subtracting the width of the body (not including scroll bar) from the width of the window (including the scroll bar). I use this to add it to the 100% of the body, see plusScrollBar variable.
JS:
// calculate width of scrollbar and add it as inline-style to the body
var checkScrollBars = function() {
var b = $('body');
var normalw = 0;
var scrollw = 0;
normalw = window.innerWidth;
scrollw = normalw - b.width();
var plusScrollBar = 'calc(' + '100% + ' + scrollw + 'px)'
document.querySelector('body').style.minWidth = plusScrollBar;
}();
CSS:
html{
overflow-x: hidden;
}
Why I like this: it takes in consideration that not all scrollbars are the same width or considered as conserved space at all. :)

I had the same issue and it was fixed when I added:
html, body { overflow-y: auto; }
I added the comment:
/* this fixes a 100vw issue, removing the horizontal scrollbar when it's unneeded */
It works at least with Firefox, Chrome, Opera and Internet Explorer 11 (I used browserling for IE).
I don't know why it works and if it works in all cases, though.
EDIT:
The horizontal scrollbar disappeared, but I noticed it's still horizontally scrollable using the cursor keys and touch screens...

overflow-x: clip; does the job.

I had the same problem. When I changed the vw units to percentage, horizontal scrollbar disappeared.

If you're working in a framework (ASP.NET for example) where there's possibly a parent element wrapping around the html, then setting the html's max-width to 100% will solve the problem without using the "band-aid" solution overflow-x: hidden.
html {
max-width: 100%;
}

An element with width: 100vw only causes horizontal scrollbars when one of it's parents has a horizontal padding. Otherwise it should fit in well.
Check this fiddle: http://jsfiddle.net/1jh1cybc/ The .parent2 has a padding, which causes the inner .box to break out of it's parent width.
Edit:
In your case I guess your body has a margin. Check this fiddle out with you code and try to remove the body css rule: http://jsfiddle.net/1jh1cybc/1/

Here's what I do:
div.screenwidth{
width:100%; /* fallback for browsers that don't understand vw or calc */
width: calc(100vw - 17px); /* -17 because vw is calculated without the scrollbar being considered & 17px is width of scrollbars */
position:relative; /* use this if the parent div isn't flush left */
right: calc((100vw - 17px - 100% )/2);
}

I fixed this on my site by adding body{overflow-x:hidden} to the page in question.
Works on your example too.

Here's my solution to the problem of 100vw adding a horizontal scroll:
html {
width: calc(100% + calc(100vw - 100%));
overflow-x: hidden;
}
.box {
width: calc(100% + calc(100vw - 100%));
}

Related

How can I prevent the page shifting when scrollbar is disabled [duplicate]

I have a website with center-aligned DIV. Now, some pages need scrolling, some don't. When I move from one type to another, the appearance of a scrollbar moves the page a few pixels to the side. Is there any way to avoid this without explicitly showing the scrollbars on each page?
overflow-y:scroll is correct, but you should use it with the html tag, not body or else you get a double scrollbar in IE 7
So the correct css would be:
html {
overflow-y: scroll;
}
Wrap the content of your scrollable element into a div and apply padding-left: calc(100vw - 100%);.
<body>
<div style="padding-left: calc(100vw - 100%);">
Some Content that is higher than the user's screen
</div>
</body>
The trick is that 100vw represents 100% of the viewport including the scrollbar. If you subtract 100%, which is the available space without the scrollbar, you end up with the width of the scrollbar or 0 if it is not present. Creating a padding of that width on the left will simulate a second scrollbar, shifting centered content back to the right.
Please note that this will only work if the scrollable element uses the page's entire width, but this should be no problem most of the time because there are only few other cases where you have centered scrollable content.
html {
overflow-x: hidden;
margin-right: calc(-1 * (100vw - 100%));
}
Example. Click "change min-height" button.
With calc(100vw - 100%) we can calculate the width of the scrollbar (and if it is not displayed, it will be 0). Idea: using negative margin-right, we can increase the width of <html> to this width. You will see a horizontal scroll bar — it should be hidden using overflow-x: hidden.
I think not. But styling body with overflow: scroll should do. You seem to know that, though.
With scroll always being shown, maybe be not good for layout.
Try to limit body width with css3
body {
width: calc(100vw - 34px);
}
vw is the width of the viewport (see this link for some explanation)
calc calculate in css3
34px stands for double scrollbar width (see this for fixed or this to calculate if you don't trust fixed sizes)
If changing size or after loading some data it is adding the scroll bar then you can try following, create class and apply this class.
.auto-scroll {
overflow-y: overlay;
overflow-x: overlay;
}
I don't know if this is an old post, but i had the same problem and if you want to scroll vertically only you should try overflow-y:scroll
body {
scrollbar-gutter: stable both-edges;
}
New css spec that will help with scrollbar repositioning is on its way:
https://developer.mozilla.org/en-US/docs/Web/CSS/scrollbar-gutter
Summary
I see three ways - each with their own quirks:
scrollbar-gutter as mentioned by Markus T.
overflow: overlay as mentioned by kunalkamble
Add spacing with calc(100vw - 100%) as mentioned Rapti
Here is a StackBlitz demo
Press the "Toggle height" to see the content shift.
scrollbar-gutter
This has limited support but with a #support media query we can use a combination of this and overflow-y: scroll:
html {
overflow-y: scroll;
}
#supports (scrollbar-gutter: stable) {
html {
overflow-y: auto;
scrollbar-gutter: stable;
}
}
In this way content will never shift.
The "problem" with this solution is that there is always a fixed space for the scrollbar.
overflow: overlay
Limited support and it obviously hides anything it overlays. Special care is needed to make sure nothing vital is hidden (also on zoom and text size changes).
Can be combined with scrollbar-gutter:
html {
overflow-y: scroll;
}
#supports (scrollbar-gutter: stable) {
html {
overflow-y: auto;
scrollbar-gutter: stable;
}
}
#supports (overflow-y: overlay) {
html {
overflow-y: overlay;
scrollbar-gutter: auto;
}
}
It is possible to do some negative margin and overflow-x: hidden but this has a risk of hiding vital content under certain situations. Small screen, custom font/zoom size, browser extensions, etc.
calc(100vw - 100%)
This can be done with RTL support like this:
html[dir='ltr'] main {
padding-left: calc(100vw - 100%);
}
html[dir='rtl'] main {
padding-right: calc(100vw - 100%);
}
Where <main> in this case would be the container for the centered content.
Content here will not shift as long as the centered container is smaller than <main>. But as soon as it is 100% of the container a padding will be introduced. See the StackBlitz demo and click "Toggle width".
The "problem" with this solution is that you need media queries to prevent padding on "small screens" and that even on small screens - when the scrollbar should be visible - some shifting will occur because there is no room for 100% content and a scrollbar.
Conclusion
Use scrollbar-gutter perhaps combined with overlay. If you absolutely don't want empty spacing, try the calc solution with media queries.
Simply setting the width of your container element like this will do the trick
width: 100vw;
This will make that element ignore the scrollbar and it works with background color or images.
#kashesandr's solution worked for me but to hide horizontal scrollbar I added one more style for body. here is complete solution:
CSS
<style>
/* prevent layout shifting and hide horizontal scroll */
html {
width: 100vw;
}
body {
overflow-x: hidden;
}
</style>
JS
$(function(){
/**
* For multiple modals.
* Enables scrolling of 1st modal when 2nd modal is closed.
*/
$('.modal').on('hidden.bs.modal', function (event) {
if ($('.modal:visible').length) {
$('body').addClass('modal-open');
}
});
});
JS Only Solution (when 2nd modal opened from 1st modal):
/**
* For multiple modals.
* Enables scrolling of 1st modal when 2nd modal is closed.
*/
$('.modal').on('hidden.bs.modal', function (event) {
if ($('.modal:visible').length) {
$('body').addClass('modal-open');
$('body').css('padding-right', 17);
}
});
I've solved the issue on one of my websites by explicitly setting the width of the body in javascript by the viewport size minus the width of the scrollbar. I use a jQuery based function documented here to determine the width of the scrollbar.
<body id="bodyid>
var bodyid = document.getElementById('bodyid');
bodyid.style.width = window.innerWidth - scrollbarWidth() + "px";
Extending off of Rapti's answer, this should work just as well, but it adds more margin to the right side of the body and hides it with negative html margin, instead of adding extra padding that could potentially affect the page's layout. This way, nothing is changed on the actual page (in most cases), and the code is still functional.
html {
margin-right: calc(100% - 100vw);
}
body {
margin-right: calc(100vw - 100%);
}
Expanding on the answer using this:
body {
width: calc(100vw - 17px);
}
One commentor suggested adding left-padding as well to maintain the centering:
body {
padding-left: 17px;
width: calc(100vw - 17px);
}
But then things don't look correct if your content is wider than the viewport. To fix that, you can use media queries, like this:
#media screen and (min-width: 1058px) {
body {
padding-left: 17px;
width: calc(100vw - 17px);
}
}
Where the 1058px = content width + 17 * 2
This lets a horizontal scrollbar handle the x overflow and keeps the centered content centered when the viewport is wide enough to contain your fixed-width content
If the width of the table won't change, you can set the width of the element (such as tbody) that contains the scrollbar > 100% (allowing extra space for the scrollbar) and set overflow-y to "overlay" (so that the scrollbar stays fixed, and won't shift the table left when it appears). Also set a fixed height for the element with the scrollbar, so the scrollbar will appear once the height is exceeded. Like so:
tbody {
height: 100px;
overflow-y: overlay;
width: 105%
}
Note: you will have to manually adjust the width % as the % of space the scrollbar takes up will be relative to your table width (ie: smaller width of table, more % required to fit the scrollbar, as it's size in pixels is constant)
A dynamic table example:
function addRow(tableID)
{
var table = document.getElementById(tableID);
var rowCount = table.rows.length;
var row = table.insertRow(rowCount);
var colCount = table.rows[0].cells.length;
for(var i=0; i<colCount; i++)
{
var newRow = row.insertCell(i);
newRow.innerHTML = table.rows[0].cells[i].innerHTML;
newRow.childNodes[0].value = "";
}
}
function deleteRow(row)
{
var table = document.getElementById("data");
var rowCount = table.rows.length;
var rowIndex = row.parentNode.parentNode.rowIndex;
document.getElementById("data").deleteRow(rowIndex);
}
.scroll-table {
border-collapse: collapse;
}
.scroll-table tbody {
display:block;
overflow-y:overlay;
height:60px;
width: 105%
}
.scroll-table tbody td {
color: #333;
padding: 10px;
text-shadow: 1px 1px 1px #fff;
}
.scroll-table thead tr {
display:block;
}
.scroll-table td {
border-top: thin solid;
border-bottom: thin solid;
}
.scroll-table td:first-child {
border-left: thin solid;
}
.scroll-table td:last-child {
border-right: thin solid;
}
.scroll-table tr:first-child {
display: none;
}
.delete_button {
background-color: red;
color: white;
}
.container {
display: inline-block;
}
body {
text-align: center;
}
<!DOCTYPE html>
<html lang="en">
<head>
<link rel="stylesheet" href="test_table.css">
</head>
<body>
<h1>Dynamic Table</h1>
<div class="container">
<table id="data" class="scroll-table">
<tbody>
<tr>
<td><input type="text" /></td>
<td><input type="text" /></td>
<td><input type="button" class="delete_button" value="X" onclick="deleteRow(this)"></td>
</tr>
</tbody>
</table>
<input type="button" value="Add" onclick="addRow('data')" />
</div>
<script src="test_table.js"></script>
</body>
</html>
I tried to fix likely the same issue which caused by twitter bootstrap .modal-open class applied to body. The solution html {overflow-y: scroll} doesn't help. One possible solution I found is to add {width: 100%; width: 100vw} to the html element.
I use to have that problem, but the simples way to fix it is this (this works for me):
on the CSS file type:
body{overflow-y:scroll;}
as that simple! :)
The solutions posted using calc(100vw - 100%) are on the right track, but there is a problem with this: You'll forever have a margin to the left the size of the scrollbar, even if you resize the window so that the content fills up the entire viewport.
If you try to get around this with a media query you'll have an awkward snapping moment because the margin won't progressively get smaller as you resize the window.
Here's a solution that gets around that and AFAIK has no drawbacks:
Instead of using margin: auto to center your content, use this:
body {
margin-left: calc(50vw - 500px);
}
Replace 500px with half the max-width of your content (so in this example the content max-width is 1000px). The content will now stay centered and the margin will progressively decrease all the way until the content fills the viewport.
In order to stop the margin from going negative when the viewport is smaller than the max-width just add a media query like so:
#media screen and (max-width:1000px) {
body {
margin-left: 0;
}
}
Et voilà!
After trying most of the above CSS or JS-based solutions that haven't worked in my case, just wanted to add up to it.
My solution worked for the case where the scrollbar had to disappear on an event (e.g. a button click, cause you've just opened a full-screen menu that should block the page from being scrollable).
This should work when the below styles are applied to the element that turns overflow-y to hidden (in my case it's the body tag):
body {
overflow-x: hidden;
width: 100vw;
margin-right: calc(100vw - 100%);
}
Explanation: The width of your body tag is 100vw (so it includes the scrollbar's width).
By setting the margin-right, the margin only gets applied if your vertical scrollbar is visible (so your page content isn't actually under the scrollbar), meaning the page content will not reposition once overflow-y has changed.
Note: this solution only works for the pages that are not horizontally-scrollable.
Tested on Chrome 89.0, Firefox 87.0, Safari 14.0.3
Update: unfortunately it only works with centered container that doesn't take 100% width - otherwise the scrollbar overlays the piece of content on the right.
My approach is to make the track transparent. The scroll bar thumb color is #C1C1C1 to match the default scrollbar thumb color. You can make it anything you prefer :)
Try this:
html {
overflow-y: scroll;
}
body::-webkit-scrollbar {
width: 0.7em;
background-color: transparent;
}
body::-webkit-scrollbar-thumb {
background: #C1C1C1;
height:30px;
}
body::-webkit-scrollbar-track-piece
{
display:none;
}
I know the question is very old, but there is a new better method.
scrollbar-gutter: stable;
I tried overflow scroll but it didn't work for my case. the scroll bar still adds some kind of (white) padding. what works is changing the width from 100vw to 100%, but for the height it is ok to use 100vh. so this:
const Wrapper = styled.div`
min-height: 100vh
`
const Parent = styled.div`
width: 100%
`
const Children = styled.div`
width: 100%
`
Edit
I've set the width twice because the parent component held a sidebar, and the children. Depending on your use case, you can set it once.
Since I haven't found my solution here I would like to add it:
I did not want a permanent scrollbar (accepted solution) and I also decided to not use negative margins. They didn't (instantly) work for me in chrome and I also did not want to have content possibly disappearing below the scrollbar.
So this is a padding solution.
My web page consists of three parts:
Header (content is left aligned)
MainContent (content is centered)
Footer (content is left and right aligned)
Since the header would look bad with a left padding and since the logo should stay in the corner of the page, I kept it unchanged since the appearing of a scrollbar does not affect it in most cases (except when window width is very small).
Since an even padding is acceptable for both the MainContent and the footer I used only for those both containers the following css:
.main-content, .footer {
/*
* Set the padding to the maximum scrollbar width minus the actual scrollbar width.
* Maximum scrollbar width is 17px according to: https://codepen.io/sambible/post/browser-scrollbar-widths
*/
padding-right: calc(17px - (100vw - 100%));
padding-left: 17px;
}
This will keep the MainContent in the exact center and also work for all scrollbar width up to 17px. One could add a media query removing these paddings for mobile devices that have an overlay scrollbar.
This solution is similar to only adding the left padding and setting the width to "width: calc(100vw - 17px);". I cannot say if it would behave equally in all cases though.
I used some jquery to solve this
$('html').css({
'overflow-y': 'hidden'
});
$(document).ready(function(){
$(window).load(function() {
$('html').css({
'overflow-y': ''
});
});
});
#media screen and (min-width: 1024px){
body {
min-height: 700px
}
}
Contrary to the accepted answer which suggests a permanent scroll bar on the browser window even if the content doesn't overflow the screen, I would prefer using:
html{
height:101%;
}
This is because the appearance of scroll bar makes more sense if the content actually overflows.
This makes more sense than this.

100vw causing horizontal overflow, but only if more than one?

Say you have this:
html, body {margin: 0; padding: 0}
.box {width: 100vw; height: 100vh}
<div class="box">Screen 1</div>
You'll get something that fills the screen, no scrollbars. But add another:
<div class="box">Screen 1</div>
<div class="box">Screen 2</div>
You get not only vertical scrollbars (expected), but a slight horizontal scroll.
I realize you could omit the width, or set it to width: 100%, but I'm curious why this is happening. Isn't 100vw supposed to be "100% of the viewport width"?
As already explained by wf4, the horizontal scroll is present because of the vertical scroll. which you can solve by giving max-width: 100%.
.box {
width: 100vw;
height: 100vh;
max-width:100%; /* added */
}
Working Fiddle
scrollbars will be included in the vw so the horizontal scroll will be added to allow you to see under the vertical scroll.
When you only have 1 box, it is 100% wide x 100% tall. Once you add 2, its 100% wide x 200% tall, therefore triggering the vertical scrollbar. As the vertical scrollbar is triggered, that then triggers the horizontal scrollbar.
You could add overflow-x:hidden to body
html, body {margin: 0; padding: 0; overflow-x:hidden;}
.box {width: 100vw; height: 100vh; background-color:#ff0000}
.box2 {width: 100vw; height: 100vh; background-color:#ffff00}
http://jsfiddle.net/NBzVV/
I had a similar problem and came up with the following solution using JS and CSS variables.
JS:
function setVw() {
let vw = document.documentElement.clientWidth / 100;
document.documentElement.style.setProperty('--vw', `${vw}px`);
}
setVw();
window.addEventListener('resize', setVw);
CSS:
width: calc(var(--vw, 1vw) * 100);
1vw is a fallback value.
If you're working in a framework (ASP.NET for example) where there's possibly a parent element wrapping around the html, then setting the html's max-width to 100% will solve the problem without using the "band-aid" solution overflow-x: hidden.
html {
max-width: 100%;
}
The reason why 100vw is causing a horizontal scrollbar is well explained in other responses: 100vw counts the width of the vertical scrollbar to the html itself. I think this is a little absurd, but it is what it is, you know :)
Update: As of Chrome version 66, I cannot reproduce the behaviour reported by question anymore. No workaround appears to be needed.
Original Answer
This is actually a bug as reported in this answer and the comments above.
While the workaround in the accepted answer (adding .box {max-width: 100%;}) generally works, I find it noteworthy that it does not currently work for display:table (tested in Chrome). In that case, the only workaround I found is to use width:100% instead.
Broken Fiddle with display:table
Working Fiddle with display:table and width:100%
to get rid of the scrollbar width included in vw i had to do this:
html, body {
overflow-x: hidden;
height: 100vh;
}
*,
html,
body {
margin: 0;
padding: 0;
overflow: hidden;/*add This*/
}
/*and enjoy ^_^ */
You can try:
*{ box-sizing: border-box}
the reason why the content is flowing out of screen is maybe you have extra padding or border on the div and it cause the content out of the broswer

Inconsistent percentage margin calculation for absolutely positioned item

I have a situation where I have a 'bottom' content div within a general container. This div should stay at the bottom (with absolute positioning), but have a percentage gap to base of the container. The percentage should be relative to the width of the container.
We can't use 'bottom:5%' because as the position props define this is relative to the height. How about margin? Yes! It works in Chrome .. and Firefox. Ah, but not in Safari. It seems Chrome and Safari calculate it based on the container width and Safari on the container height.
See this fiddle in Chrome and Safari and you'll see the inconsistency. CSS styles:
.container {
background: #990000;
width: 345px;
height: 200px;
position: relative;
}
.bottom {
background: #000;
width: 100%;
height: 40px;
position: absolute;
bottom: 0;
margin-bottom: 5%;
}
Anybody know where the bug lies here - with Safari? Chrome/Firefox? The spec?
A quick check shows that padding might work consistently, but it's not ideal for those who would want to use margin (i.e. when a background comes into play).
The problem lies with Safari. W3C Standards state that margins that are defined using percentages should be calculated with respect to the width of the containing block (not the height).
Check it: http://www.w3.org/TR/2011/REC-CSS2-20110607/box.html#margin-properties
So basically, you're stuck with the bug. However, I'd suggest using some JS to target Safari, get the width of the container and apply a margin as a percentage of that width.
For example:
var width = $('.container').width(); // get the width of div.container
var bottomMargin = width * 0.05; // multiply the width by 0.05 to get 5% of the container width
// look to see if the browser is Safari
if (navigator.userAgent.indexOf('Safari') != -1 && navigator.userAgent.indexOf('Chrome') == -1) {
$('.bottom').css('margin-bottom', bottomMargin+'px'); // apply our margin to div.bottom
}
else {
};;
I had some trouble implementing this in JS Fiddle so have created a page here.
Hope that helps!
I had the same problem with Android Browsers and was able to solve it by putting the margin on a child element.
.bottom {
position: absolute;
bottom: 0;
width: 100%;
height: 40px;
}
.bottom-child {
height:100%;
margin-bottom: 5%;
background: #000;
}
The key is not to put the margin on the absolutely positioned element.

How to make a flexible-height modal with fixed header

I've created a really simple modal that allows the content to decrease or expand without running off the page - always leaving 10% margin on the top and bottom. When the page isn't tall enough to contain all the modal content, the entire modal becomes scrollable.
See jsfiddle here
Is it possible, using only CSS, to replicate this behavior but only have the modal body be scrollable, so the header is always fixed. I've tried a few things, but haven't come up with the solution yet. Making the header position: fixed almost works, I have to reposition it over the modal box and then try to add padding to the body so the content is visible under the header, which doesn't budge the scrollbars down. I always prefer to exhaust all the css alternatives before I bind some js to window resize and manually manipulate the body height.
This might be late, but I had to solve a similar issue of fixed header, fluid height, fluid width.
This is how I tackled the issue:
Give your elements a border-box box-sizing. Use a wrapper to center and create a bounding box. This can be a fluid one with min-width and max-width + percentages.
Give your content element an overflow-y of auto and a max-height of 100%;
Use box-sizing:border-box;
The complete code should be something like this:
* {
margin: 0;
padding: 0;
box-sizing: border-box;
}
.modal {
position: fixed;
width: 100%;
height: 100%;
background-color: rgba(0,0,0,0.8);
}
.wrap {
position: relative;
margin: 0 auto;
display: block;
width: 90%;
/* Change the max-width value on a media query breakpoint to make this example more "responsive" */
max-width: 500px;
height: 90%;
padding: 30px;
}
.modal header {
height: 30px;
padding: 0;
color: #FFF;
background-color: #007;
}
.modal .body {
background-color: #FFF;
max-height: 100%;
overflow-y: auto;
}
http://jsfiddle.net/mariomc/EhR7r/
Applying the max-height and overflow-y settings to .body rather than to .wrap...?
Edit 1:
Nothing's turned up so far within the constraints, which suggests either JavaScript or straying from the constraints (using % for the header height or px margins).
Edit 2:
Here's an initial demo using % for the header height. I added a px min-height to the header tag to prevent the header from almost disappearing on very small screens, at the expense of the top margin (which is reduced on very small screens).
On a screen >= 400px tall, it should work exactly as per the requirements (40px header with 10% height). If the header were reduced in height, it would support slightly-smaller screens (a 30px header with 10% height would support >= 300px screens). Here's a demo with a 30px header.
It's a clumsy solution, but it's the only one that turned up without using JavaScript.
Also, note that I added an h2 and a .content tag and moved the padding:10px; there, to avoid combining % height and padding in the same elements (which leads to a taller height than the % value specified).

html - how to make a scroll with the width on auto?

I have a div with lots of content in it, and trying to set a width to be 100% of the parent element. This div also uses a padding, so I thought I should be setting the width to auto.
But for some reason it always expands past the parent width. I even have overflow set to scroll.
What I want is the div to have a scroll bar (only horizontal), and its width to fit the parent width.
Does anyone know how I can fix this?
100% width of its parent, with padding:
Given that the padding you mention is applied to the 100% wide element, the problem is within the box model that browsers use. If you apply 100% width and some padding, the element will get width + padding as its complete width, thus causing it to become too large. There are a few ways to solve this:
CSS3 introduces a new property called box-sizing, by setting it to border-box, the padding will be added within the given width of the element, instead of adding to the width causing the element to become "to big". (Notice the lack of support by older browsers).
I believe it would be possible to use left: 0; right: 0; instead of using width: 100%;. In that case you can add padding, without the element becoming to wide.
The second option in practice:
<!-- The markup -->
<div class="parent">
<div class="child">Child</div>
</div>​
/* The CSS */
.parent {
width: 200px;
height: 200px;
position: relative;
background-color: #666;
}
.child {
position: absolute;
left: 0;
right: 0;
padding: 10px;
background-color: #888;
}
​
Here is a working example of the second option: http://jsfiddle.net/mGLRD/
Horizontal scroll-bar:
To get a horizontal scroll-bar, you will have to look in to the overflow-x CSS-property. By setting it to scroll, you will see a disabled scrollbar when there is no content to scroll, so the scrollbar is always visible. Your other option is to set it to auto, where the scrollbar will become visible if needed (may vary between different browsers).
Try:
div#content {
width:auto;
padding:20px;
overflow-x:auto;
}
See my demo: http://jsfiddle.net/HRRsU/3/
box-sizing: border-box;
-webkit-box-sizing: border-box;
-moz-box-sizing: border-box;
http://www.w3schools.com/cssref/css3_pr_box-sizing.asp

Resources