Размещение объектов на странице XHTML - PullRequest
0 голосов
/ 09 июня 2011

Я создаю пользовательский веб-интерфейс для веб-приложения. Интерфейс имеет верхний и нижний колонтитулы и между двумя прямоугольниками в горизонтальной линии. Прямоугольники разделены пробелом. Все эти функции созданы с использованием тегов. Ниже приведен CSS для форматирования левого прямоугольника:

#sidebar1 {    
    position: absolute; 
    left: 150px;
    width: 450px;          
    height:250px;
    background: #EBEBEB; 
    padding: 20px 0; 
        padding-left:20px;
        padding-right:20px;
    margin: 50px auto;
        border: 1px solid #000000;

}

Проблема в том, что когда вы сжимаете или расширяете окно браузера, эти прямоугольники меняют положение или перекрывают друг друга. Это не приемлемо. Я пробовал другие варианты ключевых слов позиции в CSS, такие как позиция: фиксированная или позиция: относительная или статическая, но представление по-прежнему неверно. Точно так же я попробовал float: left и float: right, но это все еще заставляет прямоугольники двигаться и перекрываться. Я хочу, чтобы эти прямоугольники стояли на месте, несмотря на то, что вы расширяете или сжимаете окно. Каковы ваши решения, пожалуйста? С наилучшими пожеланиями enter image description here

Текущий код:

<html xmlns="http://www.w3.org/1999/xhtml">
    <head>
        <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
        <title>Welcome to Spring Web MVC project</title>
    <style type="text/css"> 


body {
    font: 100% Verdana, Arial, Helvetica, sans-serif;   
    margin: 0; /* it's good practice to zero the margin and padding of the body element to account for differing browser defaults */
    /*padding: 0;
    text-align: center; /* this centers the container in IE 5* browsers. The text is then set to the left aligned default in the #container selector */
    color: black;
} 

 #header { 
    background: green;         
      /*  top: 100px; */
        text-align: center;
    margin: 55px;        
    padding: 0 10px;  /* this padding matches the left alignment of the elements in the divs that appear beneath it. If an image is used in the #header instead of text, you may want to remove the padding. */
} 


#sidebar1 {    
    position: absolute;         
        left: 150px;
    width: 450px; /* since this element is floated, a width must be given */
    height:250px;
    background: #EBEBEB; /* the background color will be displayed for the length of the content in the column, but no further */
    padding: 20px 0; /* top and bottom padding create visual space within this div */
        padding-left:20px;
        padding-right:20px;
    margin: 50px auto;
        border: 1px solid #000000;

}
 #sidebar2 {
    position: absolute;        
        right: 150px;
    width: 450px; /* since this element is floated, a width must be given */
    height: 250px;
    background: #EBEBEB; /* the background color will be displayed for the length of the content in the column, but no further */
    padding: 20px 0; /* top and bottom padding create visual space within this div */
        padding-left:20px;
        padding-right:20px;
    margin: 50px auto;
        border: 1px solid #000000;

}




 #footer { 
    padding: 0 10px; /* this padding matches the left alignment of the elements in the divs that appear above it. */
    background:green;
        width:95%;
        margin:55px;
        position: relative;
        bottom: -300px;;

} 

.clearfloat { /* this class should be placed on a div or break element and should be the final element before the close of a container that should fully contain a float */
    clear:both;
    height:0px;
    font-size: 1px;
    line-height: 0px;
}


</style><!--[if IE]>
<style type="text/css"> 
/* place css fixes for all versions of IE in this conditional comment */
.thrColHybHdr #sidebar1, .thrColHybHdr #sidebar2 { padding-top: 30px; }
.thrColHybHdr #mainContent { zoom: 1; padding-top: 15px; }
/* the above proprietary zoom property gives IE the hasLayout it needs to avoid several bugs */
</style>
<![endif]--></head>

<body>
<div id="header">
    <h1>Header</h1>
  <!-- end #header --></div>
<!--<div id="container"> -->

 <div id="sidebar1">
    <h3>blah blah</h3>
    <p><li>blah blah</li> </p>
    <p><li>blah blah</li> </p>
    <p><li>blah blah</li></p>
  <!-- end #sidebar1 --></div> 

 <div id="sidebar2">
    <h3>blah blah</h3>
    <p><li>blah blah</li> </p>
    <p><li>blah blah </li></p>
    <p><li>blah blah</li></p>
  <!-- end #sidebar2 --></div>
  <p>
    <!-- This clearing element should immediately follow the #mainContent div in order to force the #container div to contain all child floats -->
  </p>


  <p><br class="clearfloat" />
  </p>
  <div id="footer">
    <p>Footer</p>
    <p>Terms & Conditions</p>

  <!-- end #footer --></div>
<!-- end #container --> <!--</div> -->
</body>
</html>

1 Ответ

2 голосов
/ 09 июня 2011

Нет никаких оснований для абсолютного положения чего-либо здесь ... это только приведет к головным болям.В общем, делайте абсолютную позицию только тогда, когда это абсолютно необходимо, что для меня почти исключительно в тех случаях, когда мне приходится плавать над чем-то другим.В противном случае все относительно чего-то другого, как по умолчанию.

Вот простая стратегия, чтобы сделать эту работу:

<div class="pagecontainer">
     <div class="header">
       Header Goes Here
     </div>

     <div class="bodycontainer">
        <div class="floatleft">Leftbox</div>
        <div class="floatleft">Rightbox</div>
        <div class="clear"></div>
     </div>

     <div class="footer">
       Footer Goes Here
     </div>
</div>

Стиль следует:

.floatleft {
   float: left;
   otherstyle: here;
   margin: 5px;
}

.clear {
   clear:both;
}

Да, это абстрактно, так что вам придется настраивать его для ваших конкретных целей.

Ключом к тому, чтобы избежать наложений, является то, чтобы ваши div в контейнере body никогда не превышали размер родительского элемента bodycontainer (donне забывайте поля и, в некоторых случаях, отступы (глупый IE) учитываются до этого значения) и то, что оба всплывают влево с чистым плаванием после этого.

Если вы хотите сделать это страшно простым, используйте сетку, такую ​​как 960.gs

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...