feetwet feetwet - 1 month ago 15
CSS Question

CSS to wrap contents in stylized container?

I have a stylesheet that specifies a style for

<LABEL>
.

But some
<LABEL>
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>
</LABEL>


I suspect there's a way to specify a CSS class, perhaps called
rightlabel
, 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
rightlabel
in CSS to produce the overridden
<LABEL>
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>
</LABEL>


but not on

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


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

Answer

Define your styles like so:

<style> 
.rightLabel
{
    text-align:right;
}

.rightLabel div 
{
    padding-right:20px;
}
</style>

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 {
  display:block;
  content:' ';
  width:20px;
  float:right;
}

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....

Comments