border-width

Any way to limit border length?

Is there any way to limit the length of a border. I have a

that has a bottom border, but I want to add a border on the left of the
that only stretches half of the way up. Is there any way to do so without adding extra elements on the page?

10 Answers 10

CSS generated content can solve this for you:

div < position: relative; >/* Main div for border to extend to 50% from bottom left corner */ div:after

(note — the content: «»; declaration is necessary in order for the pseudo-element to render)

Keep in mind: you cannot manage pseudo-elements properties from JS (actually you can, but it will be very hacky). So if you planning to make a kind of progress-bar with this solution — forget. Choose already accepted answer. In all other cases this answer is better, that’s true.

Is this cross-browser and/or JS compatible? I prefer the accepted answer, because of @SergeyPanfilov’s comment.

This may have marginal cross browser compatibility benefits over ancient browsers and is easier to control via JS. but neither of these are concerns of the original question. However this does add an additional element to the markup which the original question specifically asks to avoid. So I don’t understand why this is the accepted answer for this question.

Читайте также:  Размер окна html код

this is one of the problems with stackoverflow, the old answer was this, it is the accepted answer because it was correct for its time. The correct answer for our time is to use :after, the second answer to this question should be set to be the accepted answer.

If you play a bit you can even set your resized border element to appear centered or to appear only if there is another element next to it (like in menus). Here is an example with a menu:

#menu > ul > li < position: relative; float: left; padding: 0 10px; >#menu > ul > li + li::after
#menu > ul > li < position: relative; float: left; padding: 0 10px; list-style: none; >#menu > ul > li + li::after

With CSS properties, we can only control the thickness of border; not length.

However we can mimic border effect and control its width and height as we want with some other ways.

With CSS (Linear Gradient):

We can use linear-gradient() to create a background image(s) and control its size and position with CSS so that it looks like a border. As we can apply multiple background images to an element, we can use this feature to create multiple border like images and apply on different sides of element. We can also cover the remaining available area with some solid color, gradient or background image.

Required HTML:

All we need is one element only (possibly having some class).

  1. Create background image(s) with linear-gradient() .
  2. Use background-size to adjust the width / height of above created image(s) so that it looks like a border.
  3. Use background-position to adjust position (like left , right , left bottom etc.) of the above created border(s).

Necessary CSS:

With linear-gradient() we can create borders of solid color as well as having gradients. Below are some examples of border created with this method.

Example with border applied on one side only:

.container < display: flex; >.box < background-image: linear-gradient(purple, purple), linear-gradient(steelblue, steelblue); background-repeat: no-repeat; background-size: 4px 50%, calc(100% - 4px) 100%; background-position: left bottom, 4px 0; height: 160px; width: 160px; margin: 20px; >.gradient-border

Example with border applied on two sides:

.container < display: flex; >.box < background-image: linear-gradient(purple, purple), linear-gradient(purple, purple), linear-gradient(steelblue, steelblue); background-repeat: no-repeat; background-size: 4px 50%, 4px 50%, calc(100% - 8px) 100%; background-position: left bottom, right top, 4px 0; height: 160px; width: 160px; margin: 20px; >.gradient-border

Example with border applied on all sides:

.container < display: flex; >.box < background-image: linear-gradient(purple, purple), linear-gradient(purple, purple), linear-gradient(purple, purple), linear-gradient(purple, purple), linear-gradient(steelblue, steelblue); background-repeat: no-repeat; background-size: 4px 50%, 50% 4px, 4px 50%, 50% 4px, calc(100% - 8px) calc(100% - 8px); background-position: left bottom, left bottom, right top, right top, 4px 4px; height: 160px; width: 160px; margin: 20px; >.gradient-border

Источник

border-width

Задает толщину границы одновременно на всех сторонах элемента или индивидуально для каждой стороны. Способ изменения толщины зависит от числа значений.

Синтаксис

border-width: [значение | thin | medium | thick] | inherit

Значения

Три переменные — thin (2 пиксела), medium (4 пиксела) и thick (6 пикселов) задают толщину границы. Для более точного значения, толщину можно указывать в пикселах или других единицах. inherit наследует значение родителя.

Разрешается использовать одно, два, три или четыре значения, разделяя их между собой пробелом. Эффект зависит от количества и приведен в табл. 1.

Табл. 1. Зависимость результата от числа значений

Число значений Результат
1 Толщина границы будет установлена для всех сторон элемента.
2 Первое значение устанавливает толщину верхней и нижней границы, второе — левой и правой.
3 Первое значение задает толщину верхней границы, второе — одновременно левой и правой границы, а третье — нижней границы.
4 Поочередно устанавливается толщину верхней, правой, нижней и левой границы.

HTML5 CSS2.1 IE Cr Op Sa Fx

       

Lorem ipsum dolor sit amet, consectetuer adipiscing elit, sed diem nonummy nibh euismod tincidunt ut lacreet dolore magna aliguam erat volutpat.

Результат данного примера показан на рис. 1.

Применение свойства border-width

Рис. 1. Применение свойства border-width

Объектная модель

[window.]document.getElementById(» elementID «).style.borderWidth

Браузеры

Браузер Internet Explorer до шестой версии включительно при толщине границы 1px отображает dotted как dashed . При толщине 2px и выше значение dotted работает корректно. Эта ошибка исправлена в IE7, но только для всех границ толщиной 1px. Если одна из границ блока имеет толщину 2px и выше, то в IE7 значение dotted превращается в dashed .

Internet Explorer до версии 7.0 включительно не поддерживает значения hidden и inherit .

Толщина границы при использовании ключевых слов thin , medium и thick в разных браузерах может несколько различаться.

Не выкладывайте свой код напрямую в комментариях, он отображается некорректно. Воспользуйтесь сервисом cssdeck.com или jsfiddle.net, сохраните код и в комментариях дайте на него ссылку. Так и результат сразу увидят.

CSS по категориям

Поля

Анимация

Градиент

Скруглённые уголки

Изображения

Псевдоэлементы

Псевдоклассы

Печать

Контент

Интерфейс

Таблица

Отступы

Список

Текст

Шрифт

Форматирование

Размеры

Позиционирование

Границы

Цвет и фон

Селекторы

  • Селекторы тегов
  • Идентификаторы
  • Классы
  • Мультиклассы
  • Универсальный селектор
  • Вложенные селекторы
  • Дочерние селекторы
  • Соседние селекторы
  • Родственные селекторы
  • [атрибут=»значение»]
  • [атрибут^=»значение»]
  • [атрибут$=»значение»]
  • [атрибут*=»значение»]
  • [атрибут~=»значение»]
  • [атрибут|=»значение»]
  • Селекторы атрибутов

Источник

How to Limit Border Length with CSS

Sometimes, you may have difficulty when you need to make the border shorter than its parent element. To overcome this, use CSS properties and HTML elements. We’ll need to use border properties and some elements such as , , etc., or pseudo-elements.

The solution is quite easy. The idea is to create another «invisible» div inside the desired div, and just make the border for the inside div. In order for this solution to work, you need to place the child div very carefully, as it will be shown below.

Create HTML

div id="box"> div id="borderLeft"> div> div>

Add CSS

  • Style the with an id «box» by using the height, width, and background properties. Set the position to “relative” and specify the border-bottom property. This will be the parent div. We want the bottom border of this div to be shown completely, but the left border we just want the bottom-half of it to be shown.
  • Style the with an id «borderLeft» by specifying its border-left property. Set the position to “absolute” and add the top and bottom properties. This is the child div. By showing the border of this div, we make the limited-length border of the parent div.
#box < height: 70px; width: 70px; position: relative; border-bottom: 2px solid #0004ff; background: #cccaca; > #borderLeft < border-left: 2px solid #0004ff; position: absolute; top: 50%; bottom: 0; >

Let’s see the result of our code.

Example of limiting the left border:

html> html> head> title>Title of the document title> style> #box < height: 70px; width: 70px; position: relative; border-bottom: 2px solid #0004ff; background: #cccaca; > #borderLeft < border-left: 2px solid #0004ff; position: absolute; top: 50%; bottom: 0; > style> head> body> div id="box"> div id="borderLeft"> div> div> body> html>

Result

Next, we’re going to demonstrate another example, where we limit the border length of four different elements. For that, we use four elements and the :before pseudo-element. To limit the length of the top, bottom, right, and left borders, we use the border-top, border-bottom, border-right, and border-left properties, respectively.

Example of limiting the borders using pseudo-elements:

html> html> head> title>Title of the document title> style> h1 < text-align: center; margin: 50px; color: #000; > div < width: 150px; height: 60px; position: relative; z-index: 1; background-color: #ffff3b; margin: 20px auto; padding: 20px; color: #726E97; > div.top:before < content: ""; position: absolute; left: 0; top: 0; height: 5px; width: 50%; border-top: 3px solid #000; > div.bottom:before < content: ""; position: absolute; left: 25px; bottom: 0; height: 15px; width: 70%; border-bottom: 3px solid #000; > div.left:before < content: ""; position: absolute; left: 0; top: 0; height: 50px; width: 50%; border-left: 3px solid #000; > div.right:before < content: ""; position: absolute; right: 0; top: 0; height: 50px; width: 50%; border-right: 3px solid #000; > style> head> body> h1>Example of limiting border length h1> div class="top"> div> div class="bottom"> div> div class="left"> div> div class="right"> div> body> html>

How about moving the box itself?

If you want to move the box itself around on the page, you can use the position and left / top properties. Here’s an example:

html> html> head> style> .box < width: 300px; height: 200px; border: 1px solid #ccc; border-radius: 7px / 7px; padding: 20px; text-align: center; position: absolute; left: 50px; top: 50px; > style> head> body> div class="box"> h1>Hello, world! h1> p>This is a box with rounded corners. p> div> body> html>

In this example, we have a div element with the class box . We’ve used CSS to set the width, height, border, padding, corner radius, and text alignment of the box, as well as to position it absolutely on the page using the position , left , and top properties. The left property specifies the horizontal position of the box (in this case, 50 pixels from the left edge of the screen), and the top property specifies the vertical position of the box (in this case, 50 pixels from the top edge of the screen).

You can adjust the left and top values to move the box to a different position on the page. For example, if you want the box to be positioned 100 pixels from the left edge of the screen and 200 pixels from the top edge of the screen, you can set the left and top values accordingly:

How about creating a box with rounded corners?

Here’s a full example of how to create a box with rounded corners with a maximum radius of 7 pixels:

html> html> head> style> .box < width: 300px; height: 200px; border: 1px solid #ccc; border-radius: 7px / 7px; padding: 20px; text-align: center; > style> head> body> div class="box"> h1>Hello, world! h1> p>This is a box with rounded corners. p> div> body> html>

In this example, we have a div element with the class box . We’ve used CSS to set the width, height, border, and padding of the box, as well as to set a corner radius of 7 pixels horizontally and vertically. We’ve also centered the text inside the box using the text-align property.

Источник

CSS border-width Property

The border-width property sets the width of an element’s four borders. This property can have from one to four values.

  • border-width: thin medium thick 10px;
    • top border is thin
    • right border is medium
    • bottom border is thick
    • left border is 10px
    • top border is thin
    • right and left borders are medium
    • bottom border is thick
    • top and bottom borders are thin
    • right and left borders are medium
    • all four borders are thin

    Note: Always declare the border-style property before the border-width property. An element must have borders before you can set the width.

    Default value: medium
    Inherited: no
    Animatable: yes. Read about animatable Try it
    Version: CSS1
    JavaScript syntax: object.style.borderWidth=»1px 5px» Try it

    Browser Support

    The numbers in the table specify the first browser version that fully supports the property.

    CSS Syntax

    Property Values

    Value Description Demo
    medium Specifies a medium border. This is default Demo ❯
    thin Specifies a thin border Demo ❯
    thick Specifies a thick border Demo ❯
    length Allows you to define the thickness of the border. Read about length units Demo ❯
    initial Sets this property to its default value. Read about initial
    inherit Inherits this property from its parent element. Read about inherit

    More Examples

    Example

    Set the width of the borders to medium:

    Example

    Set the width of the borders to thick:

    Example

    Set the width of the borders to 1px:

    Example

    Set the width of the borders to 15px:

    Example

    Set the width of the top and bottom borders to 10px, and the width of the left and right borders to 1px:

    Источник

Оцените статью