Подтвердить что ты не робот

Могу ли я иметь разные цветные левые и верхние границы в CSS с прямым соединением?

Я хотел бы иметь границу с 4px толщиной розовый слева и 1px серый в другом месте:

border: 1px solid #E5E5E5;
border-left: 4px solid #F24495;

Проблема в том, что соединение диагонально, поэтому я получаю ужасное оверлей. Я пробовал:

.item:before{ 
  border-left: 4px solid #F24495;
}

Но не повезло.

Пример jsFiddle

Снимок экрана

Screenshot

4b9b3361

Ответ 1

.item::before был верным подходом, но ему нужно немного поработать над единственным свойством border-left. Вам нужно сделать видимым .item (display: block; content: "";), расположить .item с левой стороны .item и растянуть его, чтобы он .item с верхней и нижней границами должным образом.

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

.item {
  display: inline-block;
  padding: 0.2em 0.3em;
  background: #f8f8f8;
  color: #454545;

  /* Set border widths with variables */
  --top-border-width: 4px;
  --bottom-border-width: var(--top-border-width);
  --left-border-width: 16px;
  --right-border-width: var(--top-border-width);

  /* Set border styles for each side */
  border-top: var(--top-border-width) solid #e4e4e4;
  border-bottom: var(--bottom-border-width) solid #e4e4e4;
  border-right: var(--right-border-width) solid #e4e4e4;

  /* Remove the left border and add blank space where the border should be placed */
  border-left: 0;
  margin-left: var(--left-border-width);

  /* Contain the ::before */
  position: relative;
}

.item::before {
  /* Give the pseudo element substance */
  display: block;
  content: "";

  /* Add a left border with a straight edge */
  border-left: var(--left-border-width) solid #f84995;

  /* Position pseudo element border where the normal border would have been placed */
  position: absolute;
  top: calc(0px - var(--top-border-width));
  bottom: calc(0px - var(--bottom-border-width));
  left: calc(0px - var(--left-border-width));
}
<h1 class="item">Gen.2</h1>

Ответ 2

это должно работать, но требует дополнительной разметки:

.outer {
    border: 1px solid #E5E5E5;
    border-left: 0;
}

.inner {
    border-left: 4px solid #F24495;
}

и

<div class="outer">
    <div class="inner">
        ...
    </div>
</div>

Ответ 3

Если вы хотите использовать псевдо-селектор :before, вам также необходимо установить некоторый контент. См., Например, этот jsfiddle со следующим примером кода:

<div>Container</div>

CSS

div {
    border: 10px solid black;
    border-left-width: 0;
}
div::before {
    border: 10px solid orange;
    border-right-width: 0;
    content: '';
}

Отображается как:

Screenshot from working code

Edit
Хм, хотя это должно строго ответить на вопрос, пытаясь приспособить мое решение в вопросительном скрипке, я считаю, что это не очень хорошо сочетается с прокладками. Открытые для предложений/правки/другие ответы, которые могут обрабатывать этот бит: (...

Ответ 4

Фон

По умолчанию CSS использует стыки под углом (углы 45 °) для всех стыков границ. Следовательно, чтобы получить квадратные соединения (углы 90 °) для любой границы, вы можете использовать (1) внутреннюю тень блока, (2) псевдоэлементы или (3) фоновое изображение и несколько линейных градиентов.

Предположим, у вас есть следующий элемент, который вы хотите стилизовать:

<div></div>

Вариант 1: квадратные швы с использованием box-shadow

div {
  /* downside of using box-shadow, you need to add the   */
  /* inner border size to the padding on top of any      */
  /* additional padding you might want                   */
  padding: 20px;
  /* by changing the order of your box-shadows, you      */
  /* can modify which borders overlap each other         */
  box-shadow:
    /* left "inner border" */
    inset 20px 0 0 0 red,
    /* right "inner border" */
    inset -20px 0 0 0 grey,
    /* top "inner border" */
    inset 0 20px 0 0 grey,
    /* bottom "inner border" */
    inset 0 -20px 0 0 grey;
}

Вариант 2: квадратные стыки pseudo-elements

div {
  border: 20px solid grey;
}

div::before {
  position: absolute;
  background-color: red;
  content: "";
  width: 20px;
  /* we need to add the height of the top and bottom    */
  /* border to the pseudo-elements' height as the       */
  /* inset border is not included in the height of the  */
  /* div even when "box-sizing: border-box" is set.     */
  height: calc(100% + 20px + 20px);
  top: -20px;
  left: -20px;
}

Вариант 3: квадратные соединения с использованием background-image и нескольких linear-gradients

div {
  /* downside of using multiple linear-gradients, you   */
  /* need to add the inner border size to the padding   */
  /* on top of any additional padding you might want    */
  padding: calc(20px + 10px);
  background-image: 
    /* left "inner border" */
    linear-gradient(to right, red 20px, transparent 20px),
    /* right "inner border" */
    linear-gradient(to left, grey 20px, transparent 20px),
    /* top "inner border" */
    linear-gradient(grey 20px, transparent 20px),
    /* bottom "inner border" */
    linear-gradient(to top, grey 20px, transparent 20px);
}