web page elements overlapping each other even when using percentage values in css

匿名 (未验证) 提交于 2019-12-03 02:30:02

问题:

I have a page with structure like this. I want to divide the page into 6 sections so I have made 6 outer divs.

<body> <div id="header">   <img /> </div> <div id="pageTitle"> title of page </div> <div id="section1" class="section">   <div class="section-title">   section 1   </div>   <form>   <input />   </form> </div> <div id="section2" class="section">   <div class="section-title">   section 2   </div>   <form>   <input />   </form> </div> <div id="section3" class="section">   <div class="section-title">   section 3   </div>   <form>   <input />   </form> </div> <div id="nav"> <a href="url" /> </div> </body> 

the problem is that when i try to zoom into the page by using Ctrl++ in firefox or chrome the contents of the divs get overlapped on each other even when I am specifying all properties like top,width,height,left in percentages. now because percentages are relative units this should not happen.

#header { position:absolute; top:2%; width:90%; height:50%; }  #pageTitle { position:absolute; top:30%; left:20em; }  .section { margin:20px; border:10px; width:60%; height:33%; }  .section-title { position:absolute; font-size:1.4em; left:70%; margin:10px; top:10%; width:60%; height:15% }  #section1 { position:absolute; top:40%; }  #section2 { position:absolute; top:70%; }  #section3 { position:absolute; top:100%; }  form { position:absolute; top:30%; height:70%; }  label { display:block; width:75%; font-size:1em; }  #nav { position:absolute; top:140%; } 

In some other page where I was using pixels instead of percentages the content didn't overlap on zooming into the page but pixels are absolute units. What's wrong?

Pixels are the dots on the screen so when I zoom in do pixels become bigger?

回答1:

Its the box model.

Margin's extend past width and borders. It's easier to see when you're not using percents.

Say you have a div and it's CSS is:

.myDiv{margin:5px;width:100px;} 

In reality on the page, your .myDiv is 110px wide and 110px high.

Since you're using absolute positioning, the browser is overlapping because it's putting things exactly where you told it to. Hopefully that makes sense.

I'd say get rid of the margin's and try using padding instead to control the spacing. If you're trying to do stuff with backgrounds, you might have to nest a child div in there and apply the background to that instead to get the same effect.

You can check out the W3 School site for a quick and dirty overview.



回答2:

You can try this css code to fix that

section{     position: relative;     height: 100%; } 


易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!