HTML: white space around elements, how to remove?

2019-02-21 15:04发布

My webpage contains several divs. Some are set to width: 100%, so they fill the whole page width. But at the top of the page there is a small whitespace before the first element shows up. Moreover, that same whitespace is visible left and right from elements spanning the whole page width.

I cannot figure out why. If I set:

html, body {
width: 100%;
}

then the whitespace remains but the page is just stretched out to fit the image width of a div.

Can anyone help? It's probably pretty simple but I must be overlooking something. Thank you.

EDIT: I must mention I'm using a parallax element. This uses a padding, so the image does fills the whole div and does not leave a black area on top. The HTML is:

<div class="js-background-1 container">
</div>

The CSS:

.container { 
    padding-top: 200px;
}

.js-background-1 { 
    background: transparent url(url/to/image) center 0 no-repeat;
}

And the javascript:

<script type="text/javascript">
var $window = $(window); 
var velocity = 0.4;
function update(){ 
    var pos = $window.scrollTop(); 

    $('.container').each(function() { 
        var $element = $(this); 
        var height = $element.height(); 

        $(this).css('backgroundPosition', '50% ' + Math.round((height - pos) * velocity) + 'px');
    });
}; 

$window.bind('scroll', update);

</script>

I used the tutorial from http://www.webdesign.org/how-to-create-a-parallax-scrolling-website.22336.html, so there is where it is from. I changed the HTML a bit for my website, but the rest is the same.

I saw the comment about the margin and padding set to 0, but that leads to my div to have a blank space if you don't scroll far enough.

2条回答
乱世女痞
2楼-- · 2019-02-21 15:32

The good method is to always use at the begining of the file (I forgot to metion this):

*{
    margin: 0px;
    padding: 0px;
}

This two line's at the begining of main CSS file fix many problem's that you can encounter. Hope it'll help you.

查看更多
放我归山
3楼-- · 2019-02-21 15:43

You must remove the margin on body:

body {
    padding:0;
    margin:0;
}

You can also remove padding and margin on html and body

html, body {
    padding:0;
    margin:0;
}

See it on jsfiddle

But I would not advise to use * (the universal selector)

* {
    margin: 0px;
    padding: 0px;
}

This would remove padding and margins on all elements.

查看更多
登录 后发表回答