2015-08-02 3 views
2

Я хочу, чтобы достичь макет так:растягивая DIV по горизонтали

где следующие условия выполняются всегда (независимо от ширины окна браузера):

  1. Div1 и Div2 имеют равные высоты (50%)
  2. Div 3 имеет фиксированную ширину (50 пикселей).
  3. Div1 должен заполнить всю оставшуюся ширину.
  4. div4 имеет фиксированную высоту (100px) и ширину (30px) и всегда в центре к div3 (горизонтальной

и вертикальной)

Я не хочу использовать CSS3 flex основанный дисплей должного к его недоступности в старом браузере. Я попытался использовать display:inline-block, но это не растягивает Div1 по желанию. Как я могу достичь этого макета, не используя javascript? Буду признателен за любую оказанную помощь.

ответ

0

Вы можете достичь структуру, которую вы ищете, используя силу containing blocks. Элемент с номером position:relativeposition:absoluteposition:fixed сформирует новый содержащийся блок для любых position:absolute детей.

Вы можете центрировать div4 с display:inline-block, vertical-align:middle и вспомогательный элемент.

См. Комментарии в приведенном ниже коде для объяснения того, что использует каждый объект в этом примере.

Это решение будет работать для всех основных браузеров except IE <= 7

(Demo)

#wrp { 
 
    height: 100%;   /* All of the container's height */ 
 
    position: relative;  /* Establish a containing block */ 
 
} 
 
#wrp > #top, 
 
#wrp > #bottom { 
 
    position: absolute;  /* Absolutely relative to #wrp */ 
 
    height: 50%;   /* Half of #wrp's height */ 
 
    width: 100%;   /* All of #wrp's width */ 
 
} 
 
#bottom { 
 
    bottom: 0;    /* Move the bottom half to the bottom of #wrp */ 
 
} 
 
#top > #left, 
 
#top > #right { 
 
    position: absolute;  /* Absolutely relative to #top */ 
 
    height: 100%;   /* All of #top's height */ 
 
} 
 
#left { 
 
    left: 0;    /* Stick #left to the left of #top */ 
 
    right: 50px;   /* Expand #left to 50px from the right of #top */ 
 
} 
 
#right { 
 
    right: 0;    /* Stick #right to the right of #top */ 
 
    width: 100%;   /* Make #right's width responsive */ 
 
    max-width: 50px;  /* Limit #right's width to 50px */ 
 
    padding: 10px;   /* Horizontally center the child */ 
 
    box-sizing: border-box; /* Padding included in width */ 
 
    font-size: 0;   /* Remove white-space between elements */ 
 
} 
 
#center-helper, 
 
#inner { 
 
    display: inline-block; /* vertical-align applies to inline and inline-block 
 
           sizing applies to inline-block but not inline */ 
 
    vertical-align: middle; /* Align #inner to the center of the helper */ 
 
    height: 100%;   /* #center-helper will always be full height 
 
           #inner will be responsive, see next rule */ 
 
} 
 
#inner { 
 
    max-height: 100px;  /* Limit height to 100px */ 
 
    width: 100%;   /* Parent width = 50px + padding (10px*2) = 30px */ 
 
    font-size: 12pt;  /* Restore font size from the previous fix */ 
 
} 
 

 
/* Colours and environment */ 
 
html,body{height:100%;margin:0}#bottom{background:#00b35e}#left{background:#ff000b}#right{background:#fff900}#inner{background:#00b1f5}
<div id="wrp"> 
 
    <div id="top"> 
 
     <div id="left"> 
 
     </div> 
 
     <div id="right"> 
 
      <!-- IE6&7 inline-block only applies to inline elements --> 
 
      <span id="center-helper"></span> 
 
      <span id="inner"></span>   
 
     </div> 
 
    </div> 
 
    <div id="bottom"> 
 
    </div> 
 
</div>

0

CSS3 calc() функция хороший кандидат для этого:

#div3 { 
    float: left; 
    width: 50px; 
} 

#div1 { 
    float: left; 
    width: calc(100% - 50px); 
} 

Вот example on CodePen.

+1

Будет ли она работать на старых Android (<4.0) браузеров? – Aarkan

+0

К сожалению, этого не произойдет. Для справок в будущем, [этот сайт] (http://caniuse.com/#feat=calc) - это информация о совместимости. Я считаю, что есть способ сделать это без 'calc()' и без JavaScript (что не заставляет вас использовать 'absolute', но это очень хаки, и я изо всех сил пытаюсь запомнить, как это сделать. –

+0

Действительно? чтобы объяснить почему? Этот ответ является одним из лучших кросс-браузерных решений без JavaScript, руки вниз. –

1

Позиция с абсолютами и без calc. Наслаждайтесь обновленным plunker.

* { 
    box-sizing: border-box; 
} 

html, body { 
    height: 100%; 
    margin: 0; 
    padding: 0; 
} 

.container { 
    position: relative; 
    height: 100%; 
} 

.div1, .div2, .div3, .div4 { 
    position: absolute; 
} 

.div1, .div3 { 
    top: 0; 
    bottom: 50%; 
} 

.div1 { 
    right: 50px; 
    left: 0; 
    background: red; 
} 

.div2 { 
    top: 50%; 
    right: 0; 
    bottom: 0; 
    left: 0; 
    background: green; 
} 

.div3 { 
    right: 0; 
    width: 50px; 
    background: yellow; 
} 

.div4 { 
    top: 50%; 
    right: 50%; 
    margin: -50px -15px 0 0; 
    width: 30px; 
    height: 100px; 
    background: blue; 
} 
-1

Вы можете сделать что-то вроде этого:

.container { 
 
    width: 100%; 
 
    height: 300px; 
 
} 
 
.div1 { 
 
    background: red; 
 
    height: 50%; 
 
} 
 
.div2 { 
 
    background: green; 
 
    height: 50%; 
 
} 
 
.div3 { 
 
    background: yellow; 
 
    height: 50%; 
 
    width: 50px; 
 
    float: right; 
 
} 
 

 
.div4{ 
 
    height: 100px; 
 
    width: 30px; 
 
    background: blue; 
 
    margin: auto; 
 
    position: relative; 
 
    top: 50%; 
 
    -webkit-transform: translateY(-50%); 
 
    -o-transform: translateY(-50%); 
 
    -moz-transform: translateY(-50%); 
 
    -ms-transform: translateY(-50%); 
 
    transform: translateY(-50%); 
 
}
<div class="container"> 
 
    <div class="div3"> 
 
     <div class="div4"></div> 
 
    </div> 
 
    <div class="div1"></div> 
 
    <div class="div2"></div> 
 
</div>

3

Вот мое решение (поддержка IE является IE> = 9):

CSS:

html, body { 
    height: 100%; 
} 

.row { 
    height: 50%; 
    position: relative; 
} 

.half-height { 
    height: 100%; 
} 

.red { 
    background-color: red 
} 

.yellow { 
    background-color: yellow; 
    width: 50px; 
    position: absolute; 
    right: 0; 
    top: 0; 
} 

.blue { 
    height: 100px; 
    width: 30px; 
    background-color: blue; 
    margin: 0px 10px; /* 50px - 30px = right & left margins */ 
} 

.green { 
    background-color: green 
} 

/* Use tables to vertically center the blue box */ 
.vertical-center { 
    height: 100%; 
    display: table; 
} 

.vertical-container { 
    height: 100%; 
    display: table-cell; 
    vertical-align: middle; 
} 

HTML:

<div class="row"> 
    <div class="red half-height"></div> 
    <div class="yellow half-height"> 
     <div class="vertical-center"> 
      <div class="vertical-container"> 
       <div class="blue"></div> 
      </div> 
     </div> 
    </div> 
</div> 
<div class="row"> 
    <div class="green half-height"></div> 
</div> 

Fiddle: http://jsfiddle.net/2jtu1rsn/1/

Вертикальное центрирование техники было взято отсюда:

https://css-tricks.com/centering-in-the-unknown/

Смежные вопросы