Фикс коробки 250px сверху контента с переносом контента - PullRequest
3 голосов
/ 09 июня 2010

У меня проблемы с выравниванием связанных ссылок div внутри блока текста, ровно в 250 пикселях от верхней части области содержимого, при сохранении переноса слов. Я попытался сделать это с абсолютным позиционированием, но текст в области содержимого не оборачивается вокруг содержимого.

Я бы просто исправил связанные ссылки div в контенте, однако это будет отображаться на странице статьи, поэтому я бы хотел, чтобы это было сделано без размещения в определенном месте в контенте.

Возможно ли это? Если так, может кто-нибудь помочь мне с CSS для этого?

Пример изображения желаемого внешнего вида ...

ОБНОВЛЕНИЕ: для простоты я добавил пример кода. Вы можете просмотреть это здесь: http://www.focusontheclouds.com/files/example.html.

Пример HTML:

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> 
<html xmlns="http://www.w3.org/1999/xhtml"> 
<head> 
  <title>Example Page</title> 
  <style>
    body {
      width: 400px; 
      font-family: Arial, sans-serif;
    }
    h1 {
      font-family: Georgia, serif; 
      font-weight: normal;
    }
    .relatedLinks {
      position: relative;
      width: 150px; 
      text-align: center; 
      background: #f00; 
      height: 300px; 
      float: left; 
      margin: 0 10px 10px 0;
    }
  </style> 
</head>
<body> 
  <div class="relatedLinks"><h1>Related Links</h1></div>
  <p>Lorem ipsum dolor sit amet, consectetur adipiscing elit. Nunc tempus est luctus ante auctor et ullamcorper metus ullamcorper. Vestibulum molestie, lectus sed luctus egestas, dolor ipsum aliquet orci, ac bibendum quam elit blandit nulla.</p>
  <p>In sit amet sagittis urna. In fermentum enim et lectus consequat a congue elit porta. Pellentesque nisl quam, elementum vitae elementum et, facilisis quis velit. Nam odio neque, viverra in consectetur at, mollis eu mi. Etiam tempor odio vitae ligula ultrices mollis. </p>
  <p>Donec eget ligula id augue pulvinar lobortis. Mauris tincidunt suscipit felis, eget eleifend lectus molestie in. Donec et massa arcu. Aenean eleifend nulla at odio adipiscing quis interdum arcu dictum. Fusce tellus dolor, tempor ut blandit a, dapibus ac ante. Nulla eget ligula at turpis consequat accumsan egestas nec purus. Nullam sit amet turpis ac lacus tincidunt hendrerit. Nulla iaculis mauris sed enim ornare molestie. </p>
  <p>Cum sociis natoque penatibus et magnis dis parturient montes, nascetur ridiculus mus. Maecenas non purus diam. Suspendisse iaculis tincidunt tempor. Suspendisse ut pretium lectus. Maecenas id est dui.</p>
  <p>Nunc pretium ipsum id libero rhoncus varius. Duis imperdiet elit ut turpis porta pharetra. Nulla vel dui vitae ipsum sollicitudin varius. Duis sagittis elit felis, quis interdum odio. </p>
  <p>Morbi imperdiet volutpat sodales. Aenean non euismod est. Cras ultricies felis non tortor congue ultrices. Proin quis enim arcu. Cras mattis sagittis erat, elementum bibendum ipsum imperdiet eu. Morbi fringilla ullamcorper elementum. Vestibulum semper dui non elit luctus quis accumsan ante scelerisque.</p>
</body>
</html>

Ответы [ 2 ]

2 голосов
/ 10 июня 2010

Я не думаю, что это возможно, хотя попытка решить эту забавную проблему была бы приятной, и я бы хотел оказаться ошибочным.Проблема заключается в том, что, поскольку текст должен быть перенесен, ссылки должны быть встроенными, а поскольку ссылки встроены, мы не можем контролировать расстояние между ними, не влияя на текст.

При этом я сделалпридумайте этот хак, который работает в Firefox (но не работает в Chrome и IE):

Сначала оберните содержимое статьи в div.Мой тестовый html выглядел так:

<code><div class="wrapper">
    <div class="relatedLinks">
      <ul>
      </li>Test link<li>
      </li>Another link</li>
      </ul>
    <div>
    <div class="content">
      (Some really long text)
    <div>
<div>

Затем перемещайте ссылки и злоупотребляйте некоторыми соотношениями полей и отступов, например:

<code>.wrapper {
    width: 300px;
    padding-top: 200px;
}
.content {
    margin-top: -200px;
}
.relatedLinks {
    float: left;
}
.relatedLinks ul {
    padding-right: 20px;
}

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

2 голосов
/ 10 июня 2010

ОБНОВЛЕНИЕ2:

Говорили слишком рано.browsershots.org показывает, что он работает в Opera 5 (я использовал более раннюю версию) и некоторых выпусках Safari, и (конечно) IE7 и ниже (IE8 в порядке).

ОБНОВЛЕНИЕ:

Следующий код, бесстыдно подправленный из ответа Дана М., кажется, работает в современных браузерах.

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0//EN" "http://www.w3.org/TR/REC-html40/strict.dtd">
<html>
<head>
    <title>Nice Sidebar Box</title>
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8">
    <style  type="text/css">
        .wrapper
        {
            width:              500px;
            margin:             0 30px;
            line-height:        1.5;
            padding-top:        250px;
        }
        .content
        {
            margin:             0;
            margin-top:         -250px;
        }
        .relatedLinks
        {
            height:             300px;
            width:              240px;
            margin:             0 1em;
            background-color:   red;
            float:              left;
        }
    </style>
</head>
<body>
<div class="wrapper">
    <div class="relatedLinks">
        Related links content here...
    </div>
    <div class="content">
        <p>
        Do not argue with a spouse who is packing your parachute.
        </p>
        <p>
        Three weeks ago, she learned how to drive. Last week she learned how to aim it.
        </p>
        <p>
        How, if they can't see their reflections, do vampires always get their hair so nice?
        </p>
        <p>
        My wife will buy anything marked down. Last year she bought an escalator.
        </p>
        <p>
        Sign in a men's room: "This is not urinal, it's ourinal, so please flush."
        </p>
        <p>
        She was at the beauty shop for two hours. That was only for the estimate.
        </p>
        <p>
        For those of you who've never been to Las Vegas, there the "G string" is known as the gownless
        evening strap.
        </p>
        <p>
        Hollywood's a town where they shoot entirely too many movies and not enough actors.
        </p>
        <p>
        Three weeks ago, she learned how to drive. Last week she learned how to aim it.
        </p>
        <p>
        How, if they can't see their reflections, do vampires always get their hair so nice?
        </p>
        <p>
        My wife will buy anything marked down. Last year she bought an escalator.
        </p>
        <p>
        Sign in a men's room: "This is not urinal, it's ourinal, so please flush."
        </p>
        <p>
        She was at the beauty shop for two hours. That was only for the estimate.
        </p>
        <p>
        For those of you who've never been to Las Vegas, there the "G string" is known as the gownless
        evening strap.
        </p>
        <p>
        Hollywood's a town where they shoot entirely too many movies and not enough actors.
        </p>
    </div>
</div>
</body>
</html>

Старый ответ:

Это может быть невозможно только с помощью CSS.Рассмотрим эту страницу:

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0//EN" "http://www.w3.org/TR/REC-html40/strict.dtd">
<html>
<head>
    <title>Nice Sidebar Box</title>
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8">
    <style  type="text/css">
        .content
        {
            width:              500px;
            margin:             2em;
            line-height:        1.5;
        }
        .relatedLinks
        {
            position:           relative;
            top:                250px;
            height:             300px;
            width:              240px;
            margin:             1em;
            background-color:   red;
            float:              left;
            margin-bottom:      250px;
            display:            inline-block;
        }
    </style>
</head>
<body>
<div class="content">
    <p>
    Do not argue with a spouse who is packing your parachute.
    </p>
    <div class="relatedLinks">
        Related links content here...
    </div>
    <p>
    Three weeks ago, she learned how to drive. Last week she learned how to aim it.
    </p>
    <p>
    How, if they can't see their reflections, do vampires always get their hair so nice?
    </p>
    <p>
    My wife will buy anything marked down. Last year she bought an escalator.
    </p>
    <p>
    Sign in a men's room: "This is not urinal, it's ourinal, so please flush."
    </p>
    <p>
    She was at the beauty shop for two hours. That was only for the estimate.
    </p>
    <p>
    For those of you who've never been to Las Vegas, there the "G string" is known as the gownless
    evening strap.
    </p>
    <p>
    Hollywood's a town where they shoot entirely too many movies and not enough actors.
    </p>
</div>
</body>
</html>

Обратите внимание, что поплавок правильно обрабатывается рядом с боковой панелью и под ней (все ставки отключены в IE6).

Но левое поле неверно для текставыше боковой панели - без учета первого абзаца.

Этот первый абзац появляется перед боковой панелью в html-коде.Мало того, но это ударяет боковую панель вниз - она ​​больше не в 250px.

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

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