Html 调整窗口大小时使 div 保持不变

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/18769891/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-29 13:20:47  来源:igfitidea点击:

Making divs stay the same place when resizing window

htmlcss

提问by user2713996

First of all im new programmer, so dont judge quickly :). Anyways ive been struggling with this problem for some time now. The problem is when im resizing(scaling whatever) the window, it messes around with ALL my elements. When resizing my website, you should just see less, than before. Not move around elements.

首先我是新程序员,所以不要快速判断:)。无论如何,我已经在这个问题上挣扎了一段时间了。问题是当我调整窗口大小(缩放任何大小)时,它会与我所有的元素混在一起。调整我的网站大小时,您应该看到的内容比以前少。不移动元素。

Here's the code:

这是代码:

HTML:

HTML:

<div id="leftblock">
   </div>



<div id="rightBlock">
</div>

CSS:

CSS:

#leftblock {   

 margin-left: 20%;
 background-color: red;
 float: left;
 height: 100px;
 width: 3px;  

}



#rightBlock { 
 margin-right: 20%;
 background-color: red;
 float: right;
 height: 100px;
 width: 3px;


}

To be sure what i mean, test the code in an editor, and then try resize the window.

为了确定我的意思,请在编辑器中测试代码,然后尝试调整窗口大小。

jsFiddled here

js在这里摆弄

回答by crush

If you don't want them to move around, place the elements in a fixed size parent container.

如果您不想让它们四处移动,请将元素放在固定大小的父容器中。

DEMO

DEMO

CSS

CSS

#container {
 width: 1000px;
}

#leftblock {   
 margin-left: 20%;
 background-color: red;
 float: left;
 height: 100px;
 width: 3px;  
}

#rightBlock { 
 margin-right: 20%;
 background-color: red;
 float: right;
 height: 100px;
 width: 3px;
}

HTML

HTML

<div id="container">
    <div id="leftblock">
    </div>

    <div id="rightBlock">
    </div>
</div>

回答by JP Lew

it's because you're using percentages for your margins. If you want them to stay in place, used a fixed unit like pxor em. For example

这是因为您的利润率使用百分比。如果您希望它们保持原位,请使用固定单元,例如pxem。例如

margin-right: 100px;