Reputation: 35
How do I create a button that's text is displayed outside the button? I want to create a list of buttons but I want the button text (the button value) to be displayed before the button so it will look something like this:
Button text here [button]
I want the button text to be left aligned and the button itself to be right aligned. I am new to CSS and have no idea if this is possible. the reason I can't just write the text separately is I am updating the style sheet for an existing project and am trying to make minimal changes to the html since the project includes multiple files. Is this possible?
Upvotes: 1
Views: 2801
Reputation: 43853
If you are only using CSS try the pseudo-element ::before and make it position:absolute
and the button position:relative
. The positions have to be adjusted according to the length of the button's text, because all lengths are relative to the button:
.btn
left: 50%;
- The position of the button itself is relative to it's original position. In the demo, the button has been moved 50% of it's parent's (ie.<body>
) width from the left..btn::before
width:300%
- The width of the pseudo-element is 3 times the width of the button.right:75%
- The position of the pseudo-element is 75% from the right edge of the button.
It's a little complex but if you don't want to use proper HTML, then be prepared for CSS shenanigans. The plus side is that the position of text and button relating to themselves is never adversely affected (unless your CSS is overtly crappy) by resizing of the viewport (i.e. resizing of the window)
.btn {
font: 400 16px/1.4 Consolas;
position: relative;
display: inline-block;
left: 50%;
}
.btn::before {
font: inherit;
content: 'Text on the left';
position: absolute;
display: inline-block;
width: 300%;
right: 70%;
}
<button class='btn' type='button'>Button</button>
Upvotes: 1
Reputation: 19111
You could try something like this, which avoids having to set an explicit width of the button. You hide the original button text and use pseudo element content to display the same string as the button.
button {
position: relative; /* make the button the parent */
}
button span {
visibility: hidden; /* hide the original button text */
}
button:after {
content: 'Button text';
position: absolute;
left: 100%; /* position text just outside the button edge */
white-space: nowrap; /* prevent wrapping */
top: 2px;
}
<button>
<span>Button text</span>
</button>
Upvotes: 2