How to add a border to only percentage of width of element, CSS Trick

13,704

Solution 1

I recreated your divider using :before/:after pseudo-elements:

http://jsfiddle.net/thirtydot/E93UE/1/

#staff_list li:first-child:before, #staff_list li:after {
    content: '';
    display: block;
    margin: auto;
    position: relative;
    bottom: -26px;
    width: 500px;
    height: 2px;
    background: #b9b7b6;
}
#staff_list li:first-child:before {
    top: -14px;
    bottom: auto;
}

The numbers need tweaking, and you need to test it when you have more text, but it's probably close enough. I made other changes to help this solution work, compare your original demo to mine.

Solution 2

Give a border to :after pseudo-element (demo):

.separated:after {
    content: "";
    display: block;
    width: 70%;
    margin: 1em auto 0;
    border-bottom: solid;
}
Share:
13,704
Ben Carey
Author by

Ben Carey

For any questions, please feel free to email me at: [email protected]

Updated on June 23, 2022

Comments

  • Ben Carey
    Ben Carey almost 2 years

    The Issue...

    Once again I am searching for a cool CSS trick to help me to achieve an effect whilst preventing the use of untidy HTML...

    The following image shows what I am trying to achieve, notice the top and bottom borders only stretching around 70% of the width...

    Percentage Width Borders

    A Starting Point

    As a starting point I have created the above using what I would call 'untidy HTML' to add these dividers to the list.

    Here is my jsFiddle: http://jsfiddle.net/E93UE/

    You will see I have <li class="divider><!-- Divider --></li>, this is what I want to get rid of if possible

    My Question

    So, if the above has not explained well enough, I would like to apply a border to a block element, but only show the border for a specific width of the whole element.

    Obviously this cannot be achieved using just border:XXX, it is likely to need some :before and :after selectors...

    Possible Solutions...

    I have had two thoughts of how this could be achieved, one is not too practical, and the other I am not too sure how to implement (these are just ideas):

    1. Set the width of the list element and give it overflow:visible, all elements within have position:absolute and then just apply margins to bring the elements out of the list box... (not a good fix, prefer my original)
    2. The other solution, which I am not too sure how to implement, may be the way to go. By apply two :before elements with position:absolute you could overlay the edges of each border (I think)