使用一个以“ div”为中心对齐的网页。我经历了一堆方法来尝试使其以我想要的方式工作,最后找到了最接近的方法。我在这里有一个工作演示
FIDDLE
我现在唯一的问题是,即使内容没有占据页面的全部内容,它仍然会添加滚动条。我想知道是否可以删除它?我相信这与将“ div”居中的jQuery方法有关。
Javascript:
$(function() {
jQuery.fn.center = function() {
this.css("position", "fixed");
this.css("top", ($(window).height() / 2) - (this.outerHeight() / 2));
this.css("left", ($(window).width() / 2) - (this.outerWidth() / 2));
return this;
}
$('#myDiv').center();
$(window).resize(function() {
$('#myDiv').center();
});
});
的CSS
* {
margin: 0;
padding: 10px;
}
html,
body {
height: 100%;
}
body {
font-family: 'Josefin Sans';
text-align: center;
}
p {
font-size: 18px;
margin: 0 0 0.5em;
}
.centered-wrapper {
display: flex;
flex-direction: column;
justify-content: center;
min-height: 100%;
}
.centered {
background: #ccc;
border-radius: 8px;
margin: 0 auto;
padding: 20px;
width: 85%;
}
最佳答案
将溢出设置为隐藏可能会解决滚动条不出现的问题,但在这种情况下,滚动条可能不会完全垂直居中。
相反,您无法像对那样对所有元素设置填充
* {
margin: 0;
padding: 10px;
}
它会使您的body元素和.content-wrapper具有额外的10px填充,从而增加其高度并显示滚动条,如果将该填充设置为0,则滚动条会消失,请检查小提琴。
因此,对于您的示例,您可以将CSS设置为
body, html {
margin: 0;
padding: 0;
}
p, h1, h2, h3, h4, span, br, hr {
margin: 0px;
padding: 10px;
}
html,
body {
height: 100%;
margin: 0;
}
body {
font-family: 'Josefin Sans';
text-align: center;
}
p {
font-size: 18px;
margin: 0 0 0.5em;
}
.centered-wrapper {
display: flex;
flex-direction: column;
justify-content: center;
min-height: 100%;
}
.centered {
background: #ccc;
border-radius: 8px;
margin: 0 auto;
padding: 20px;
width: 85%;
}
/*
Button
*/
.btn {
-webkit-border-radius: 8;
-moz-border-radius: 8;
border-radius: 8px;
font-family: Arial;
color: black;
font-size: 18px;
background: #ccc;
padding: 10px 20px 10px 20px;
text-decoration: none;
outline: none;
}
.btn:hover {
background: #bbb;
text-decoration: none;
}
在这种情况下,滚动条将不会出现。
不要在所有元素上使用*设置边距和填充,而应使用CSS样式重置之类的方法。 Google。然后,仅对您真正需要的元素应用填充。
关于javascript - 如何删除页面上的滚动条,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/38578188/