How to adjust the border length using CSS?

This div element has a shortened border

When we add a border to an element, it takes up its full width. However, there might be situations where you need to adjust the length of the border.

For example, You want to add a border to the bottom of the element but you don’t want this border under the whole element. Instead, you need only some part of it say 50%.

Well, in CSS there is no such property as border-length that allows you to directly adjust the border length. In this tutorial, we are going to learn an easy method that we can use to adjust the border length.

An easy approach of doing this is to make use of CSS ::before or ::after pseudo-elements and apply the desired border to these pseudo-elements.

To adjust the border length, you can use the width & height properties of these pseudo-elements.

In the following example, we have added a blue bottom border to the div element and we have shortened it to 50% by setting the width of the ::before element to 50%.

Example:

div{
   position: relative;
   font-size: 2rem;
}
div::before{
   content: '';
   position: absolute;
   bottom: 0;
   left: 0;
   border-bottom: 2px solid blue;
   width: 50%;
}

The position of the border can be easily adjusted using the top, left, bottom and right properties.

In the following example, we have the placed the same old border on the top of the div element using top: 0; & left: 0;

This div element has a shortened border

Example:

div{
   position: relative;
   font-size: 2rem;
}
div::before{
   content: '';
   position: absolute;
   top: 0;
   left: 0;
   border-bottom: 2px solid blue;
   width: 50%;
}

I hope now you can easily adjust the border length as well as its position.

Author

  • Manoj Kumar

    Hi, My name is Manoj Kumar. I am a full-stack developer with a passion for creating robust and efficient web applications. I have hands-on experience with a diverse set of technologies, including but not limited to HTML, CSS, JavaScript, TypeScript, Angular, Node.js, Express, React, and MongoDB.