feetwet feetwet - 11 months ago 64
CSS Question

CSS to wrap contents in stylized container?

I have a stylesheet that specifies a style for


But some
s are special: Currently I inline style them like this:

<LABEL style="text-align:right; line-height:15pt">
<div style="padding-right:20px">My Label Text</div>

I suspect there's a way to specify a CSS class, perhaps called
, to render the preceding using something simple like this:

<LABEL class="rightlabel">My Label Text</LABEL>

What would the correct way be to do that? I.e., is there a way to define
in CSS to produce the overridden
while automatically wrapping its children in a padded child container (because the style doesn't work correctly unless that is done, and it doesn't seem proper to depend on the coder to implement two elements to get the style right)?

Amendment: I can get most of the way there using a child selector – as shown in this fiddle with this CSS:

.rightLabel {text-align: right}
.rightLabel > * {padding-right: 20px}

But I can't find a way to apply the padding to the label contents without explicitly wrapping the contents in some container. I.e., the above CSS works correctly on

<LABEL class="rightLabel">
<div>This is what we wanted!</div>

but not on

<LABEL class="rightLabel">Why am I not padded?</LABEL>

Is it possible to apply a style to the
contents without explicitly coding them inside another HTML element (child)?

Answer Source

Define your styles like so:


.rightLabel div 

Update to updated question: you can't add a div using CSS, you'll need JavaScript. You can add pseudo elements using :before and :after.

Here's a fiddle https://jsfiddle.net/c3h9a2b9/1/

.rightLabel:before {
  content:' ';

This fakes the padding by using the :before or :after pseudo element on your label. It needs a display of block (inline-block would also do) and some dimensions, the width here being 20px (the "padding" that you need) and floated in the direction you want padding....