Подскажите, как сверстать такой бордер?
7 ответов
UPD: обновил решение, теперь все адаптивно.
.abc {
border: 5px solid #000;
background-color: #fff;
position: relative;
z-index: 1;
padding: 5px;
}
.abc::after,
.abc::before {
content: "";
display: block;
border: 5px solid #fff;
z-index: 20;
position: absolute;
}
.abc::after {
left: -5px;
top: 10px;
right: -5px;
bottom: 10px;
border-top: none;
border-bottom: none;
}
.abc::before {
left: 10px;
top: -5px;
right: 10px;
bottom: -5px;
border-left: none;
border-right: none;
}
<div class="abc">
Proin eget tortor risus. Vestibulum ac diam sit amet quam vehicula elementum sed sit amet dui. Praesent sapien massa, convallis a pellentesque nec, egestas non nisi. Vestibulum ac diam sit amet quam vehicula elementum sed sit amet dui. Praesent sapien massa, convallis a pellentesque nec, egestas non nisi. Quisque velit nisi, pretium ut lacinia in, elementum id enim. Donec rutrum congue leo eget malesuada. Nulla quis lorem ut libero malesuada feugiat. Donec rutrum congue leo eget malesuada. Vestibulum ac diam sit amet quam vehicula elementum sed sit amet dui.
</div>
-
@Geyan это легко поправить. Нужно для сокрытия испольозвать бордеры псевдо элементов а не их
background-color
. См. мой ответ.– Arnial21 июл 2016 в 1:16 -
Можно через фоновую картинку квадрата в *.png и border-image-slice
#borderimg1 {
border: 10px solid transparent;
padding: 15px;
border-image: url("https://i.stack.imgur.com/7SexA.png") round;
border-image-slice: 20;
}
<p id="borderimg1">для квадрата 40x40 border-image-slice: 20;</p>
<p>Here is the image used:</p>
<img src="https://i.stack.imgur.com/7SexA.png">
Основан на ответе @slippyk, но позволяет свободно маштабировать текст внутри дива + текст внутри дива виден (исправлено замечание @Geyan).
Прекрасно работает с любыми padding
, width
и height
(в том числе auto
и 100%
, но нужно чтобы текст вмещался в div
полностью).
Ограничение: нельзя сделать overflow
отличный от visible
.
.abc {
width: 200px;
height: 100%;
border: 5px solid #000;
position: relative;
background-color: white;
}
.abc::after,
.abc::before {
content: "";
display: block;
background-color: transparent;
z-index: 20;
position: absolute;
}
.abc::after {
width: 100%;
height: calc(100% - 20px);
left: -5px;
top: 10px;
border-left: 5px solid white;
border-right: 5px solid white;
}
.abc::before {
width: calc(100% - 20px);
height: 100%;
left: 10px;
top: -5px;
border-top: 5px solid white;
border-bottom: 5px solid white;
}
<div class="abc">
Proin eget tortor risus. Vestibulum ac diam sit amet quam vehicula elementum sed sit amet dui. Praesent sapien massa, convallis a pellentesque nec, egestas non nisi. Vestibulum ac diam sit amet quam vehicula elementum sed sit amet dui. Praesent sapien
massa, convallis a pellentesque nec, egestas non nisi. Quisque velit nisi, pretium ut lacinia in, elementum id enim. Donec rutrum congue leo eget malesuada. Nulla quis lorem ut libero malesuada feugiat. Donec rutrum congue leo eget malesuada. Vestibulum
ac diam sit amet quam vehicula elementum sed sit amet dui.
</div>
Текст добавлен для теста, блок тянется и содержимое выталкивает низ!
html,
body {
height: 100%;
}
.div {
width: 700px;
height: 200px;
min-height: 200px;
background: blue;
margin: 10px auto;
position: relative;
}
.top {
width: 100%;
height: 50%;
background: #fff;
position: relative;
}
.bottom {
width: 100%;
min-height: 50%;
background: #fff;
position: relative;
}
.top:after {
content: '';
position: absolute;
border: 30px solid #000;
z-index: -1;
left: -1px;
top: -1px;
}
.top:before {
content: '';
position: absolute;
border: 30px solid #000;
z-index: -1;
right: -2px;
top: -1px;
}
.bottom:after {
content: '';
position: absolute;
border: 30px solid #000;
z-index: -1;
bottom: -1px;
left: -1px;
}
.bottom:before {
content: '';
position: absolute;
border: 30px solid #000;
z-index: -1;
right: -2px;
bottom: -1px;
}
.content {
width: 100%;
min-height: 200px;
margin: auto;
background: #fff;
}
.content p {
display: block;
width: 90%;
margin: auto;
text-align: justify;
padding: 10px;
font-size: 18px;
}
<div class="div">
<div class="top"></div>
<div class="content">
<p>
Mauris blandit aliquet elit, eget tincidunt nibh pulvinar a. Lorem ipsum dolor sit amet, consectetur adipiscing elit. Lorem ipsum dolor sit amet, consectetur adipiscing elit. Praesent sapien massa, convallis a pellentesque nec, egestas non nisi. Nulla
porttitor accumsan tincidunt. Proin eget tortor risus. Quisque velit nisi, pretium ut lacinia in, elementum id enim. Vivamus suscipit tortor eget felis porttitor volutpat. Lorem ipsum dolor sit amet, consectetur adipiscing elit. Praesent sapien
massa, convallis a pellentesque nec, egestas non nisi.
</p>
<p>
Mauris blandit aliquet elit, eget tincidunt nibh pulvinar a. Lorem ipsum dolor sit amet, consectetur adipiscing elit. Lorem ipsum dolor sit amet, consectetur adipiscing elit. Praesent sapien massa, convallis a pellentesque nec, egestas non nisi. Nulla
porttitor accumsan tincidunt. Proin eget tortor risus. Quisque velit nisi, pretium ut lacinia in, elementum id enim. Vivamus suscipit tortor eget felis porttitor volutpat. Lorem ipsum dolor sit amet, consectetur adipiscing elit. Praesent sapien
massa, convallis a pellentesque nec, egestas non nisi.
</p>
</div>
<div class="bottom"></div>
</div>
Я немного припозднился, посмотрите и мой вариант:
.wrapper {
height: 220px; /* высота блока с рамкой */
width: 220px; /* ширина блока с рамкой */
position: relative;
margin: auto; /* для красоты расположения */
}
.left_top {
height: 50px;
width: 50px;
background-color: black;
position: absolute;
}
.left_bottom {
height: 50px;
width: 50px;
background-color: black;
position: absolute;
top: 170px;
}
.right_top {
height: 50px;
width: 50px;
background-color: black;
position: absolute;
left: 170px;
}
.right_bottom {
height: 50px;
width: 50px;
background-color: black;
position: absolute;
left: 170px;
top: 170px;
}
.general {
position: absolute;
height: 200px;
width: 200px;
background-color: white;
left: 10px; /* ширина */
top: 10px; /* рамки */
}
<div class="wrapper">
<div class="left_top"></div>
<div class="left_bottom"></div>
<div class="right_top"></div>
<div class="right_bottom"></div>
<div class="general">
text text text text text text text text text text text text text text text text text text
</div>
</div>
Остальные ответы страдают тем, что основаны на перекрытии границей сплошного цвета (например, белого) идентичного фону, а значит если на родительских элементах будет фон картинкой или градиент, то они перекроются этой границей.
Также многие ответы довольно громоздки, требуют множество стилей и разметки и не очень сопровождаемы из-за большого количества фиксированных значений.
Можно воспользоваться несколькими градиентами в одном background
. Результат:
div {
/* отступы чтобы границы не налазили на контент */
padding: 25px;
/* стили чисто для демонстрации */
margin: 20px;
/* устанавливаем фиксированную ширину и высоту чисто для демонстрации */
width: 300px;
height: 200px;
background:
linear-gradient(to right, #000 50px, transparent 0, transparent calc(100% - 50px), #000 0) 0 0 / 100% 10px no-repeat,
linear-gradient(to right, #000 50px, transparent 0, transparent calc(100% - 50px), #000 0) 0 100% / 100% 10px no-repeat,
linear-gradient(to bottom, #000 50px, transparent 0, transparent calc(100% - 50px), #000 0) 0 0 / 10px 100% no-repeat,
linear-gradient(to bottom, #000 50px, transparent 0, transparent calc(100% - 50px), #000 0) 100% 0 / 10px 100% no-repeat;
}
<div></div>
Очень легко можно внутрь добавить текст:
div {
/* отступы чтобы "границы" не налазили на контент */
padding: 25px;
/* стили чисто для демонстрации */
margin: 20px;
background:
linear-gradient(to right, #000 50px, transparent 0, transparent calc(100% - 50px), #000 0) 0 0 / 100% 10px no-repeat,
linear-gradient(to right, #000 50px, transparent 0, transparent calc(100% - 50px), #000 0) 0 100% / 100% 10px no-repeat,
linear-gradient(to bottom, #000 50px, transparent 0, transparent calc(100% - 50px), #000 0) 0 0 / 10px 100% no-repeat,
linear-gradient(to bottom, #000 50px, transparent 0, transparent calc(100% - 50px), #000 0) 100% 0 / 10px 100% no-repeat;
}
<div>Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s, when an unknown printer took a galley of type and scrambled it to make a type specimen book. It has
survived not only five centuries, but also the leap into electronic typesetting, remaining essentially unchanged. It was popularised in the 1960s with the release of Letraset sheets containing Lorem Ipsum passages, and more recently with desktop publishing
software like Aldus PageMaker including versions of Lorem Ipsum. Why do we use it? It is a long established fact that a reader will be distracted by the readable content of a page when looking at its layout. The point of using Lorem Ipsum is that it
has a more-or-less normal distribution of letters, as opposed to using 'Content here, content here', making it look like readable English. Many desktop publishing packages and web page editors now use Lorem Ipsum as their default model text, and a search
for 'lorem ipsum' will uncover many web sites still in their infancy. Various versions have evolved over the years, sometimes by accident, sometimes on purpose (injected humour and the like). Where does it come from? Contrary to popular belief, Lorem
Ipsum is not simply random text. It has roots in a piece of classical Latin literature from 45 BC, making it over 2000 years old. Richard McClintock, a Latin professor at Hampden-Sydney College in Virginia, looked up one of the more obscure Latin words,
consectetur, from a Lorem Ipsum passage, and going through the cites of the word in classical literature, discovered the undoubtable source. Lorem Ipsum comes from sections 1.10.32 and 1.10.33 of "de Finibus Bonorum et Malorum" (The Extremes of Good
and Evil) by Cicero, written in 45 BC. This book is a treatise on the theory of ethics, very popular during the Renaissance. The first line of Lorem Ipsum, "Lorem ipsum dolor sit amet..", comes from a line in section 1.10.32. The standard chunk of Lorem
Ipsum used since the 1500s is reproduced below for those interested. Sections 1.10.32 and 1.10.33 from "de Finibus Bonorum et Malorum" by Cicero are also reproduced in their exact original form, accompanied by English versions from the 1914 translation
by H. Rackham. Where can I get some?</div>
Демонстрация с градиентным фоном:
body {
background-image: linear-gradient(0deg, blue, red);
/* чтобы занимать минимум весь экран */
min-height: 100vh;
margin: 0;
}
div {
/* отступы чтобы границы не налазили на контент */
padding: 25px;
/* стили чисто для демонстрации */
margin: 20px;
background:
linear-gradient(to right, #000 50px, transparent 0, transparent calc(100% - 50px), #000 0) 0 0 / 100% 10px no-repeat,
linear-gradient(to right, #000 50px, transparent 0, transparent calc(100% - 50px), #000 0) 0 100% / 100% 10px no-repeat,
linear-gradient(to bottom, #000 50px, transparent 0, transparent calc(100% - 50px), #000 0) 0 0 / 10px 100% no-repeat,
linear-gradient(to bottom, #000 50px, transparent 0, transparent calc(100% - 50px), #000 0) 100% 0 / 10px 100% no-repeat;
}
<div>Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s, when an unknown printer took a galley of type and scrambled it to make a type specimen book. It has
survived not only five centuries, but also the leap into electronic typesetting, remaining essentially unchanged. It was popularised in the 1960s with the release of Letraset sheets containing Lorem Ipsum passages, and more recently with desktop publishing
software like Aldus PageMaker including versions of Lorem Ipsum. Why do we use it? It is a long established fact that a reader will be distracted by the readable content of a page when looking at its layout. The point of using Lorem Ipsum is that it
has a more-or-less normal distribution of letters, as opposed to using 'Content here, content here', making it look like readable English. Many desktop publishing packages and web page editors now use Lorem Ipsum as their default model text, and a search
for 'lorem ipsum' will uncover many web sites still in their infancy. Various versions have evolved over the years, sometimes by accident, sometimes on purpose (injected humour and the like). Where does it come from? Contrary to popular belief, Lorem
Ipsum is not simply random text. It has roots in a piece of classical Latin literature from 45 BC, making it over 2000 years old. Richard McClintock, a Latin professor at Hampden-Sydney College in Virginia, looked up one of the more obscure Latin words,
consectetur, from a Lorem Ipsum passage, and going through the cites of the word in classical literature, discovered the undoubtable source. Lorem Ipsum comes from sections 1.10.32 and 1.10.33 of "de Finibus Bonorum et Malorum" (The Extremes of Good
and Evil) by Cicero, written in 45 BC. This book is a treatise on the theory of ethics, very popular during the Renaissance. The first line of Lorem Ipsum, "Lorem ipsum dolor sit amet..", comes from a line in section 1.10.32. The standard chunk of Lorem
Ipsum used since the 1500s is reproduced below for those interested. Sections 1.10.32 and 1.10.33 from "de Finibus Bonorum et Malorum" by Cicero are also reproduced in their exact original form, accompanied by English versions from the 1914 translation
by H. Rackham. Where can I get some?</div>
Небольшая заметка:
Я использую 0
как ступенях градиентов, чтобы не дублировать предыдущие значения, так как по спецификации ступенька градиента не может быть меньше предыдущего значения.
If a color-stop has a position that is less than the specified position of any color-stop before it in the list, set its position to be equal to the largest specified position of any color-stop before it.
-
@tutankhamun Это совершенно разные ответы с разными принципами. Начало одинаковое, так как многие ответы страдают схожими недостатками. 13 сен 2017 в 13:16
-
Остальные ответы страдают тем, что основаны на перекрытии границей сплошного цвета (например, белого) идентичного фону, а значит если на родительских элементах будет фон картинкой или градиент, то они перекроются этой границей.
Также многие ответы довольно громоздки, требуют множество стилей и разметки и не очень сопровождаемы из-за большого количества фиксированных значений.
Для того, чтобы этого избежать можно использовать абсолютно позиционированные псевдоэлементы с border-image
с фиктивным градиентом (для имитации сплошного чёрного цвета), так как border-image
нельзя присвоить сплошной цвет. Используется border-image
, так как может занимать не весь периметр элемента, а также налазить на контент. Толщину и ширину уголков очень легко регулировать для данного примера. Результат:
div {
position: relative;
/* отступы чтобы границы не налазили на контент */
padding: 25px;
/* стили чисто для демонстрации */
margin: 20px;
/* устанавливаем фиксированную ширину и высоту чисто для демонстрации */
width: 300px;
height: 200px;
}
div:before,
div:after {
content: "";
/* абсолютное позицонирование */
position: absolute;
/* занимать всю ширину и высоту */
left: 0;
top: 0;
right: 0;
bottom: 0;
/* какую-нибудь границу чтобы border-image работал */
border: 1px solid;
/* устанавливаем чёрный цвет с помощью фейкового градиента */
border-image-source: linear-gradient(#000, #000);
/* толщина 10px ширина 50px */
border-image-width: 10px 50px;
}
div:after {
border-image-width: 50px 10px;
}
<div></div>
Очень легко можно внутрь добавить текст:
div {
position: relative;
/* отступы чтобы границы не налазили на контент */
padding: 25px;
/* стили чисто для демонстрации */
margin: 20px;
}
div:before,
div:after {
content: "";
/* абсолютное позицонирование */
position: absolute;
/* занимать всю ширину и высоту */
left: 0;
top: 0;
right: 0;
bottom: 0;
/* какую-нибудь границу чтобы border-image работал */
border: 1px solid;
/* устанавливаем чёрный цвет с помощью фейкового градиента */
border-image-source: linear-gradient(#000, #000);
/* толщина 10px ширина 50px */
border-image-width: 10px 50px;
}
div:after {
border-image-width: 50px 10px;
}
<div>Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s, when an unknown printer took a galley of type and scrambled it to make a type specimen book. It has
survived not only five centuries, but also the leap into electronic typesetting, remaining essentially unchanged. It was popularised in the 1960s with the release of Letraset sheets containing Lorem Ipsum passages, and more recently with desktop publishing
software like Aldus PageMaker including versions of Lorem Ipsum. Why do we use it? It is a long established fact that a reader will be distracted by the readable content of a page when looking at its layout. The point of using Lorem Ipsum is that it
has a more-or-less normal distribution of letters, as opposed to using 'Content here, content here', making it look like readable English. Many desktop publishing packages and web page editors now use Lorem Ipsum as their default model text, and a search
for 'lorem ipsum' will uncover many web sites still in their infancy. Various versions have evolved over the years, sometimes by accident, sometimes on purpose (injected humour and the like). Where does it come from? Contrary to popular belief, Lorem
Ipsum is not simply random text. It has roots in a piece of classical Latin literature from 45 BC, making it over 2000 years old. Richard McClintock, a Latin professor at Hampden-Sydney College in Virginia, looked up one of the more obscure Latin words,
consectetur, from a Lorem Ipsum passage, and going through the cites of the word in classical literature, discovered the undoubtable source. Lorem Ipsum comes from sections 1.10.32 and 1.10.33 of "de Finibus Bonorum et Malorum" (The Extremes of Good
and Evil) by Cicero, written in 45 BC. This book is a treatise on the theory of ethics, very popular during the Renaissance. The first line of Lorem Ipsum, "Lorem ipsum dolor sit amet..", comes from a line in section 1.10.32. The standard chunk of Lorem
Ipsum used since the 1500s is reproduced below for those interested. Sections 1.10.32 and 1.10.33 from "de Finibus Bonorum et Malorum" by Cicero are also reproduced in their exact original form, accompanied by English versions from the 1914 translation
by H. Rackham. Where can I get some?</div>
Демонстрация с градиентным фоном:
body {
background-image: linear-gradient(0deg, blue, red);
/* чтобы занимать минимум весь экран */
min-height: 100vh;
margin: 0;
}
div {
position: relative;
/* отступы чтобы границы не налазили на контент */
padding: 25px;
/* стили чисто для демонстрации */
margin: 20px;
}
div:before,
div:after {
content: "";
/* абсолютное позицонирование */
position: absolute;
/* занимать всю ширину и высоту */
left: 0;
top: 0;
right: 0;
bottom: 0;
/* какую-нибудь границу чтобы border-image работал */
border: 1px solid;
/* устанавливаем чёрный цвет с помощью фейкового градиента */
border-image-source: linear-gradient(#000, #000);
/* толщина 10px ширина 50px */
border-image-width: 10px 50px;
}
div:after {
border-image-width: 50px 10px;
}
<div>Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s, when an unknown printer took a galley of type and scrambled it to make a type specimen book. It has
survived not only five centuries, but also the leap into electronic typesetting, remaining essentially unchanged. It was popularised in the 1960s with the release of Letraset sheets containing Lorem Ipsum passages, and more recently with desktop publishing
software like Aldus PageMaker including versions of Lorem Ipsum. Why do we use it? It is a long established fact that a reader will be distracted by the readable content of a page when looking at its layout. The point of using Lorem Ipsum is that it
has a more-or-less normal distribution of letters, as opposed to using 'Content here, content here', making it look like readable English. Many desktop publishing packages and web page editors now use Lorem Ipsum as their default model text, and a search
for 'lorem ipsum' will uncover many web sites still in their infancy. Various versions have evolved over the years, sometimes by accident, sometimes on purpose (injected humour and the like). Where does it come from? Contrary to popular belief, Lorem
Ipsum is not simply random text. It has roots in a piece of classical Latin literature from 45 BC, making it over 2000 years old. Richard McClintock, a Latin professor at Hampden-Sydney College in Virginia, looked up one of the more obscure Latin words,
consectetur, from a Lorem Ipsum passage, and going through the cites of the word in classical literature, discovered the undoubtable source. Lorem Ipsum comes from sections 1.10.32 and 1.10.33 of "de Finibus Bonorum et Malorum" (The Extremes of Good
and Evil) by Cicero, written in 45 BC. This book is a treatise on the theory of ethics, very popular during the Renaissance. The first line of Lorem Ipsum, "Lorem ipsum dolor sit amet..", comes from a line in section 1.10.32. The standard chunk of Lorem
Ipsum used since the 1500s is reproduced below for those interested. Sections 1.10.32 and 1.10.33 from "de Finibus Bonorum et Malorum" by Cicero are also reproduced in their exact original form, accompanied by English versions from the 1914 translation
by H. Rackham. Where can I get some?</div>