我试着用JQuery使这个div居中,这样它就能响应,但我似乎做不到,我已经试过了
function resize() {
var h = $(window).height();
var w = $(window).width();
var ct = $("#content");
ct.height(h / 2.5);
ct.width(w / 2.5);
ct.css("left", w / 2);
ct.css("right", w / 2);
ct.css("top", h / 2);
ct.css("bottom", h / 2);
}
resize();
$(window).on("resize", function() {
resize();
})<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<style>
#content {
border: 1px black solid;
}
</style>
<div id="content"></div>
它根本不居中,我不知道我怎么才能居中,还能与移动设备兼容
发布于 2019-05-02 08:23:07
要使<div>居中,可以使用以下代码:
#content {
position: fixed;
top: 50%;
left: 50%;
transform: translate(-50%, -50%);
border: 1px solid black;
min-height: 20px;
min-width: 20px;
}<div id="content"></div>
而不使用任何Javascript。
发布于 2019-05-02 08:23:48
忘掉以这种方式居中的项目,只需简单地转换为flexbox
html, body {
margin: 0;
padding: 0;
}
.wrapper {
display: flex;
min-height: 100vh;
}
.wrapper .child {
margin: auto;
}<div class="wrapper">
<div class="child">
hello
</div>
</div>
发布于 2019-05-02 09:18:49
您可以在没有的情况下使用任何jQuery/JS将元素居中,这是推荐的做法。
#element {
position: absolute;
top: 50%; /* aligns element's top edge to 50% from the top edge of the page */
left: 50%; /* aligns element's left edge to 50% from the left edge of the page */
transform: translate(-50%, -50%); /* values are relative to the element's width and height */
}如果您设置了right和bottom,则不需要设置top和left。如您所见,下面的代码就足够了。
div {
width: 30px;
height: 30px;
position: absolute;
top: 50%;
left: 50%;
transform: translate(-50%, -50%);
background: black;
}<div></div>
值得注意的是,如果父元素为position: relative,则可以使用absolute使其他元素居中。例如..。
#parent {
width: 30px;
height: 30px;
position: relative;
top: 25px;
left: 75px;
background: black;
}
#child {
width: 10px;
height: 10px;
position: absolute;
left: 50%;
top: 50%;
transform: translate(-50%, -50%);
background: lime;
}<div id='parent'>
<div id='child'></div>
</div>
https://stackoverflow.com/questions/55944199
复制相似问题