9

Очень долго искал, но не нашел ответ.

Можно ли как-либо абсолютно позиционированному элементу позиционироваться относительно body, если этот элемент имеет одного или несколько абсолютно позиционированных предков?

скрин

Проблема в том, что содержимое подпапок начиная с содержимого папки 3.1 (на скрине) не растягиваются на всю длину контента а только в пределах родителя.

вот так надо (сделано на скорую в фоторедакторе(ой ошибся с очередностью папок но суть не в этом)): как надо кстати body простирается дальше вправо,просто так заскринил

Дерево папок на чекбоксах и по-другому сделать средствами css, html я не вижу как (ховеры присутствуют,но мне нужно чтобы была возможность закрепить отображения контента папок).

Есть 4 варианта решения как подсказали:

  • margin-right:-35px;
  • min-width: 75%;
  • white-space: nowrap;
  • right:10px;

К сожалению все эти способа не дают приемлемого результата. При уменьшении окна браузера не стягивается\съёживается контент адекватно. Да и выглядят тоже так себе.

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

Код громоздок, не знаю стоит ли скидывать, и куда... jsfiddle?

body {
  background-color: #2e3436;
  font-size: 100%;
}
b::selection,
a::selection,
img::selection {
  background-color: rgba(153, 204, 255, 0.5);
}
b {
  font-family: Verdana, Arial, Helvetica, sans-serif;
}
img {
  height: 16px;
  width: 16px;
  vertical-align: middle;
  background-color: #ccc;
  border: 3px solid #ccc;
  border-radius: 2px;
}
li:hover img {
  background-color: white;
  border: 3px solid white;
}
a:active {
  color: white;
  position: relative;
  top: 1px;
}
ul {
  margin: 0;
  padding: 0;
}
/*---огибание текста ссылок фавиконок---*/

li a { display: inline-block; margin-left: 25px; padding: 2px 0; } li img { /чтобы ссылки правильно огибали фавиконы/ position: absolute; } /.........../

a { color: #ccc; text-decoration: none; } a:hover { text-decoration: underline; } ul li:hover { /ul- чтобы побороть специфичность селектора/ background-color: rgba(204, 204, 204, 0.2); border-radius: 2px; box-shadow: 0 0 10px rgba(204, 204, 204, 0.2); } /------ новые точки списка ------/

ul { list-style: none; } li { position: relative; padding-left: 15px; bord er: 1px solid red; } li:before { content: ''; position: absolute; top: 9px; left: 0; width: 9px; min-height: 9px; margin-top: -4px; border-radius: 50% 14px; border: 1px solid #ccc; } li:hover:before { box-shadow: 0 0 4px rgba(225, 225, 220, 0.85); background: white; border: 1px solid white; } /---чередующяяся подсветка списка---/

li:nth-child(even) { background-color: rgba(225, 225, 220, 0.08); } /--------/// side-list ///-----------/

label { transition: 0.4s; transition-timing-function: ease-in-out; } .folder b { font-size: 90%; } .folder_c li { width: auto; cursor: default; } .folder1 { border-radius: 0 14px 0 0; } /-----точечки папок----/

label:before { content: ''; position: absolute; left: 5px; width: 9px; min-height: 9px; margin-top: 4px; border-radius: 50%; border: 1px solid #ccc; vertical-align: center; } input:checked +label:before { box-shadow: 0 0 4px rgba(225, 225, 220, 0.85); background: white; border: 1px solid white; } /---------/

.side-list { float: left; width: 150px; border: 1px solid #ccc; min-height: 150px; border-radius: 0 15px 15px 0; margin-left: 13px; } ///////////////////////////

.folder { padding: 0; border-bottom: 1px solid #ccc; color: #ccc; cursor: pointer; } .folder_c { /folder content/ display: none; background-color: rgba(46, 49, 50, 0.9); padding: 8px; max-width: 1200px; border-radius: 5px; box-shadow: 3px 3px 6px rgba(0, 0, 0, 0.50); position: absolute; left: 160px; margin-top: -25px; margin-right: 8px; border: 1px solid rgba(204, 204, 204, 0.55); padding-top: 10px; z-index: 1; /из-за кастомных точечек списков фона/ } /.........../

.folder:hover { background-color: #ccc; } .folder:hover> b { color: #2e3436; } label { display: block; padding: 5px 10px; width: auto; } input:checked + label { background-color: #ccc; color: #2e3436; } /.........../

.folder { /для лейбла чтоб выглядил как блок/ display: block; padding: 5px 10px; margin: 0; } .pre-folder:hover >.folder_c { display: block; } input:checked +label+ div { /* не удалять/ display: block; } input /:not(checked)*/

{ /* скрывает чекбокс/ position: absolute; opacity: 0; } /-----------*/

<!DOCTYPE html>
<html>

<head>
  <meta charset="UTF-8">
  <title>Bookmarks</title>
  <link href="style.css" rel="stylesheet">
</head>

<body>
  <div class="side-list">
    <input type="checkbox" id="folder1" />
    <label class="folder folder1" for="folder1">
      <b>Folder 1</b>
      <div class="folder_c">
        <ul>
          <li>
            <img width="16" src="index_files/favicon (1).ico">
            <a href="https://www.amazon.com/Monoprice-Charge-Transfer-Protection-Switch/dp/B00Y42IE76/">Amazon.com: Monoprice USB 2.0 to Micro B Sync &amp; Fast Charge Cable with Data Transfer Protection On/Off Switch - 30/20 AWG 4.5ft (1): Computers &amp; Accessories</a>
          </li>
          <li>
            <img width="16" src="index_files/favicon (2).ico">
            <a href="http://www.ebay.com/itm/USB-Male-to-Female-Charging-Switch-Data-Cable-for-Samsung-Galaxy-Tab-P7500-P7510-/271524739619?">USB Male to Female Charging Switch Data Cable for Samsung Galaxy Tab P7500 P7510 | eBay</a>
          </li>
          <li title="base64 иконка">
            <img width="16" src="">
            <a href="https://www.qwant.com/web"> Веб-сайт Qwant</a>
          </li>
          <li title="локальная иконка">
            <img width="16" src="index_files/favicon.ico">
            <a href="https://www.gigablast.com/">Gigablast - An Alternative Open Source Search Engine</a>
          </li>
          <li>
            <a href="https://search.disconnect.me/">Disconnect Search: Search privately using your favorite search engine</a>
          </li>
        </ul>
      </div>
    </label>

    <input type="checkbox" id="folder2" />
    <label class="folder" for="folder2">
      <b>FOLDER 2</b>
      <div class="folder_c">
        <ul>
          <li>
            <img width="16" src="index_files/favicon (1).ico">
            <a href="https://www.amazon.com/Monoprice-Charge-Transfer-Protection-Switch/dp/B00Y42IE76/">Amazon.com...</a>
          </li>
          <li>
            <img width="16" src="index_files/favicon (2).ico">
            <a href="http://www.ebay.com/itm/USB-Male-to-Female-Charging-Switch-Data-Cable-for-Samsung-Galaxy-Tab-P7500-P7510-/271524739619?">USB Male to Female...</a>
          </li>
        </ul>
      </div>
    </label>
    <!-- ПАПКИ ВСТАВЛЯТЬ ТУТ -->
    <!-- ТЕСТ -->
    <div class="pre-folder">
      <input type="checkbox" id="folder3" />
      <label class="folder" for="folder3">
        <b>FOLDER 3</b>
      </label>
      <div class="folder_c">
        <ul>
          <li>
            <img width="16" src="index_files/favicon (1).ico">
            <a href="https://www.amazon.com/Monoprice-Charge-Transfer-Protection-Switch/dp/B00Y42IE76/">Amazon.comrrrrrrrrrrrrrr
      rrrrrrrrrrrrrrrrrrrrrr
      rrrrrrrrrrrrrrrrrrrrrrrrr
      rrrrrrrrrrrrrrrrrrrrrr...</a>
          </li>
          <li>
            <img width="16" src="index_files/favicon (2).ico">
            <a href="http://www.ebay.com/itm/USB-Male-to-Female-Charging-Switch-Data-Cable-for-Samsung-Galaxy-Tab-P7500-P7510-/271524739619?">USB Male to Female...</a>
          </li>
          <!--2-->
          <div class="rel">
            <div class="pre-folder">
              <input type="checkbox" id="folder4" />
              <label class="folder" for="folder4">
                <b>FOLDER 3.1</b>
              </label>
              <div class="folder_c">
                <ul>
                  <li>
                    <img width="16" src="index_files/favicon (1).ico">
                    <a href="https://www.amazon.com/Monoprice-Charge-Transfer-Protection-Switch/dp/B00Y42IE76/">Amazon.comrrrrrrrrrrrrrr
         rrrrrrrrrrrrrrrrrrrrrr
         rrrrrrrrrrrrrrrrrrrrrrrrr
         rrrrrrrrrrrrrrrrrrrrrr</a>
                  </li>

                  <!--3-->
                  <div class="pre-folder">
                    <input type="checkbox" id="folder5" />
                    <label class="folder" for="folder5">
                      <b>FOLDER 3.2</b>
                    </label>
                    <div class="folder_c">
                      <ul>
                        <li>
                          <img width="16" src="index_files/favicon (1).ico">
                          <a href="https://www.amazon.com/Monoprice-Charge-Transfer-Protection-Switch/dp/B00Y42IE76/">Amazon.comrrrrrrrrrrrrrr
            rrrrrrrrrrrrrrrrrrrrrr
            rrrrrrrrrrrrrrrrrrrrrrrrr
            rrrrrrrrrrrrrrrrrrrrrr</a>
                        </li>
                        <li>
                          <img width="16" src="index_files/favicon (2).ico">
                          <a href="http://www.ebay.com/itm/USB-Male-to-Female-Charging-Switch-Data-Cable-for-Samsung-Galaxy-Tab-P7500-P7510-/271524739619?">USB Male to Female...</a>
                        </li>
                      </ul>
                    </div>
                  </div>
                  <!--3-->

                  <li>
                    <img width="16" src="index_files/favicon (2).ico">
                    <a href="http://www.ebay.com/itm/USB-Male-to-Female-Charging-Switch-Data-Cable-for-Samsung-Galaxy-Tab-P7500-P7510-/271524739619?">USB Male to Female...</a>
                  </li>
                </ul>
              </div>
            </div>
          </div>
          <!--/2-->
        </ul>
      </div>
    </div>
    <!-- /ТЕСТ -->
  </div>

</body>

</html>
qwertet
  • 129
  • Код лучше сюда. – edem Oct 24 '16 at 22:49
  • p.s. код 10 раз переделывал все еще будучи новичком по этому такой мутный. – qwertet Oct 24 '16 at 23:24
  • p.p.s. первые 2 папки не работают, я пока ими не занимался. – qwertet Oct 24 '16 at 23:25
  • Каким образом задаётся размер абсолютных папок? margin-ами? Пробовали уже убирать правый маргин? И вообще, зачем им абсолютное позиционирование, разве относительное не работает? – Sergey Oct 24 '16 at 23:53
  • задаются размеры так: max-width:1200px; left:160px; margin-top:-25px; margin-right:8px;

    по всякому пробовал маргины тут не причем . относительное? всмысле relative? не понял

    – qwertet Oct 25 '16 at 00:03
  • а если .folder-c поставить не max-width: 1200px, а min-width: 75% или даже 100%, но со 100%-ми точно за экран вылезать будет – stackanon Oct 25 '16 at 00:22
  • 1
    Нужно сделать так, чтобы текст не разбивался на несколько строк. whit-space: nowrap Тогда папка будет растягиваться по длине строки – Sergey Oct 25 '16 at 01:02
  • А вместо того, чтобы фоткать, надо просто просмотреть сайт инструментами разработчика, которые есть во всех главных браузерах – Sergey Oct 25 '16 at 01:06
  • stackanon, Sergey спасибо, оба способа работают, правда к сожалению при уменьшении окна браузера не стягивается\съёживается контент адекватно. – qwertet Oct 25 '16 at 02:57
  • но неужто нет решения по элегантнее? кроме как переосмыслить и переписать весь код..) идей как сделать по-другому к сожалению нет – qwertet Oct 25 '16 at 03:30
  • Может единицы vh и vw пригодятся, – zb' May 06 '17 at 04:22

3 Answers3

1

Эту задачу можно решить так: сделать все абсолютные блоки шириной до конца экрана, а внутрь добавить блок на ширину контента (например, inline-block). Я отредактировал ваш пример, html остался прежним, а в стилях обратите внимание на разделы: .folder_c и .folder_c>ul. По сути, я перенес из первого блока все оформление во внутренний UL.

В результате, окна показываются на всю свою ширину, но когда упираются в правый край экрана (или body, как вам угодно), то начинают сжиматься.

Надеюсь, это то что вам было нужно.

введите сюда описание изображения

body {
  background-color: #2e3436;
  font-size: 100%;
}

b::selection, a::selection, img::selection { background-color: rgba(153, 204, 255, 0.5); }

b { font-family: Verdana, Arial, Helvetica, sans-serif; }

img { height: 16px; width: 16px; vertical-align: middle; background-color: #ccc; border: 3px solid #ccc; border-radius: 2px; }

li:hover img { background-color: white; border: 3px solid white; }

a:active { color: white; position: relative; top: 1px; }

ul { margin: 0; padding: 0; }

/---огибание текста ссылок фавиконок---/

li a { display: inline-block; margin-left: 25px; padding: 2px 0; }

li img { /чтобы ссылки правильно огибали фавиконы/ position: absolute; }

/.........../

a { color: #ccc; text-decoration: none; }

a:hover { text-decoration: underline; }

ul li:hover { /ul- чтобы побороть специфичность селектора/ background-color: rgba(204, 204, 204, 0.2); border-radius: 2px; box-shadow: 0 0 10px rgba(204, 204, 204, 0.2); }

/------ новые точки списка ------/

ul { list-style: none; }

li { position: relative; padding-left: 15px; bord er: 1px solid red; }

li:before { content: ''; position: absolute; top: 9px; left: 0; width: 9px; min-height: 9px; margin-top: -4px; border-radius: 50% 14px; border: 1px solid #ccc; }

li:hover:before { box-shadow: 0 0 4px rgba(225, 225, 220, 0.85); background: white; border: 1px solid white; }

/---чередующяяся подсветка списка---/

li:nth-child(even) { background-color: rgba(225, 225, 220, 0.08); }

/--------/// side-list ///-----------/

label { transition: 0.4s; transition-timing-function: ease-in-out; }

.folder b { font-size: 90%; }

.folder_c li { width: auto; cursor: default; }

.folder1 { border-radius: 0 14px 0 0; }

/-----точечки папок----/

label:before { content: ''; position: absolute; left: 5px; width: 9px; min-height: 9px; margin-top: 4px; border-radius: 50%; border: 1px solid #ccc; vertical-align: center; }

input:checked+label:before { box-shadow: 0 0 4px rgba(225, 225, 220, 0.85); background: white; border: 1px solid white; }

/---------/

.side-list { float: left; width: 150px; border: 1px solid #ccc; min-height: 150px; border-radius: 0 15px 15px 0; margin-left: 13px; }

///////////////////////////

.folder { padding: 0; border-bottom: 1px solid #ccc; color: #ccc; cursor: pointer; }

.folder_c { /folder content/ display: none; /* background-color: rgba(46, 49, 50, 0.9); / / padding: 8px; / / max-width: 1200px; / / border-radius: 5px; / / box-shadow: 3px 3px 6px rgb(0 0 0 / 50%); / position: absolute; left: 160px; margin-top: -25px; margin-right: 8px; / border: 1px solid rgba(204, 204, 204, 0.55); / padding-top: 10px; z-index: 1; / min-width: max-content; / right: 0; /из-за кастомных точечек списков фона*/ }

/.........../

.folder_c>ul { display: inline-block; background-color: rgba(46, 49, 50, 0.9); padding: 8px; border-radius: 5px; box-shadow: 3px 3px 6px rgb(0 0 0 / 50%); /* position: absolute; / / left: 160px; / / margin-top: -25px; / / margin-right: 8px; */ border: 1px solid rgba(204, 204, 204, 0.55); padding-top: 10px; }

.folder:hover { background-color: #ccc; }

.folder:hover>b { color: #2e3436; }

label { display: block; padding: 5px 10px; width: auto; }

input:checked+label { background-color: #ccc; color: #2e3436; }

/.........../

.folder { /для лейбла чтоб выглядил как блок/ display: block; padding: 5px 10px; margin: 0; }

.pre-folder:hover>.folder_c { display: block; }

input:checked+label+div { /* не удалять*/ display: block; }

input /:not(checked)/

{ /* скрывает чекбокс*/ position: absolute; opacity: 0; }

/-----------/

<!DOCTYPE html>
<html>

<head>
  <meta charset="UTF-8">
  <title>Bookmarks</title>
  <link href="style.css" rel="stylesheet">
</head>

<body>
  <div class="side-list">
    <input type="checkbox" id="folder1" />
    <label class="folder folder1" for="folder1">
      <b>Folder 1</b>
      <div class="folder_c">
        <ul>
          <li>
            <img width="16" src="index_files/favicon (1).ico">
            <a href="https://www.amazon.com/Monoprice-Charge-Transfer-Protection-Switch/dp/B00Y42IE76/">Amazon.com: Monoprice USB 2.0 to Micro B Sync &amp; Fast Charge Cable with Data Transfer Protection On/Off Switch - 30/20 AWG 4.5ft (1): Computers &amp; Accessories</a>
          </li>
          <li>
            <img width="16" src="index_files/favicon (2).ico">
            <a href="http://www.ebay.com/itm/USB-Male-to-Female-Charging-Switch-Data-Cable-for-Samsung-Galaxy-Tab-P7500-P7510-/271524739619?">USB Male to Female Charging Switch Data Cable for Samsung Galaxy Tab P7500 P7510 | eBay</a>
          </li>
          <li title="base64 иконка">
            <img width="16" src="">
            <a href="https://www.qwant.com/web"> Веб-сайт Qwant</a>
          </li>
          <li title="локальная иконка">
            <img width="16" src="index_files/favicon.ico">
            <a href="https://www.gigablast.com/">Gigablast - An Alternative Open Source Search Engine</a>
          </li>
          <li>
            <a href="https://search.disconnect.me/">Disconnect Search: Search privately using your favorite search engine</a>
          </li>
        </ul>
      </div>
    </label>

    <input type="checkbox" id="folder2" />
    <label class="folder" for="folder2">
      <b>FOLDER 2</b>
      <div class="folder_c">
        <ul>
          <li>
            <img width="16" src="index_files/favicon (1).ico">
            <a href="https://www.amazon.com/Monoprice-Charge-Transfer-Protection-Switch/dp/B00Y42IE76/">Amazon.com...</a>
          </li>
          <li>
            <img width="16" src="index_files/favicon (2).ico">
            <a href="http://www.ebay.com/itm/USB-Male-to-Female-Charging-Switch-Data-Cable-for-Samsung-Galaxy-Tab-P7500-P7510-/271524739619?">USB Male to Female...</a>
          </li>
        </ul>
      </div>
    </label>
    <!-- ПАПКИ ВСТАВЛЯТЬ ТУТ -->
    <!-- ТЕСТ -->
    <div class="pre-folder">
      <input type="checkbox" id="folder3" />
      <label class="folder" for="folder3">
        <b>FOLDER 3</b>
      </label>
      <div class="folder_c">
        <ul>
          <li>
            <img width="16" src="index_files/favicon (1).ico">
            <a href="https://www.amazon.com/Monoprice-Charge-Transfer-Protection-Switch/dp/B00Y42IE76/">Amazon.comrrrrrrrrrrrrrr
                        rrrrrrrrrrrrrrrrrrrrrr
                        rrrrrrrrrrrrrrrrrrrrrrrrr
                        rrrrrrrrrrrrrrrrrrrrrr...</a>
          </li>
          <li>
            <img width="16" src="index_files/favicon (2).ico">
            <a href="http://www.ebay.com/itm/USB-Male-to-Female-Charging-Switch-Data-Cable-for-Samsung-Galaxy-Tab-P7500-P7510-/271524739619?">USB Male to Female...</a>
          </li>
          <!--2-->
          <div class="rel">
            <div class="pre-folder">
              <input type="checkbox" id="folder4" />
              <label class="folder" for="folder4">
                <b>FOLDER 3.1</b>
              </label>
              <div class="folder_c">
                <ul>
                  <li>
                    <img width="16" src="index_files/favicon (1).ico">
                    <a href="https://www.amazon.com/Monoprice-Charge-Transfer-Protection-Switch/dp/B00Y42IE76/">Amazon.comrrrrrrrrrrrrrr
                                    rrrrrrrrrrrrrrrrrrrrrr
                                    rrrrrrrrrrrrrrrrrrrrrrrrr
                                    rrrrrrrrrrrrrrrrrrrrrr</a>
                  </li>

                  <!--3-->
                  <div class="pre-folder">
                    <input type="checkbox" id="folder5" />
                    <label class="folder" for="folder5">
                      <b>FOLDER 3.2</b>
                    </label>
                    <div class="folder_c">
                      <ul>
                        <li>
                          <img width="16" src="index_files/favicon (1).ico">
                          <a href="https://www.amazon.com/Monoprice-Charge-Transfer-Protection-Switch/dp/B00Y42IE76/">Amazon.comrrrrrrrrrrrrrr
                                                rrrrrrrrrrrrrrrrrrrrrr
                                                rrrrrrrrrrrrrrrrrrrrrrrrr
                                                rrrrrrrrrrrrrrrrrrrrrr</a>
                        </li>
                        <li>
                          <img width="16" src="index_files/favicon (2).ico">
                          <a href="http://www.ebay.com/itm/USB-Male-to-Female-Charging-Switch-Data-Cable-for-Samsung-Galaxy-Tab-P7500-P7510-/271524739619?">USB Male to Female...</a>
                        </li>
                      </ul>
                    </div>
                  </div>
                  <!--3-->

                  <li>
                    <img width="16" src="index_files/favicon (2).ico">
                    <a href="http://www.ebay.com/itm/USB-Male-to-Female-Charging-Switch-Data-Cable-for-Samsung-Galaxy-Tab-P7500-P7510-/271524739619?">USB Male to Female...</a>
                  </li>
                </ul>
              </div>
            </div>
          </div>
          <!--/2-->
        </ul>
      </div>
    </div>
    <!-- /ТЕСТ -->
  </div>

</body>

</html>
Dzorogh
  • 620
0

Если у родителя абсолютно позиционированного элемента значение position задано как fixed, relative или absolute, то отсчет координат ведется от края родительского элемента.

  • вопрос в том, есть ли хитрости чтобы это обойти – qwertet Oct 24 '16 at 23:17
  • попробуйте включить box-sizing: border-box; для этих элементов, тогда граница будет включаться в их размер –  Oct 24 '16 at 23:21
  • к сожалению это не то ,сейчас попробую в фоторедакторе показать что я имел ввиду – qwertet Oct 24 '16 at 23:43
  • 1
    @Khipster для fixed расчёт берётся от body хоть лопни , и ни какой relative не поможет –  Oct 24 '16 at 23:58
  • приобщил изображение из фоторедактора к вопросу – qwertet Oct 25 '16 at 00:14
  • 1
    @МаксимЛенский если лопнуть с transform, то fixed ведет себя куда более странно, чем кажется, и точно не от body. – zb' May 08 '17 at 02:10
  • @zb' однако это будет не от relative ... вы согласны ? –  May 08 '17 at 02:37
0

Сочетание position: fixed и transform даёт желаемый эффект (подробнее о их взаимодействии на enSO):

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

body { width: 1000px; overflow: auto; transform: translateZ(0); }

div { position: fixed; left: 100px; right: 100px; height: 2em; background: linear-gradient(to right, blue, red); }

div::before { content: attr(style); color: white; line-height: 2em; padding-left: .5em; }

<div style="top:50px">
  <div style="top:150px">
    <div style="top:100px">
      <div style="top:800px"></div>
    </div>
  </div>  
</div>
Qwertiy
  • 123,725