Home > Software engineering >  Replace text content of <legend> tag with CSS
Replace text content of <legend> tag with CSS

Time:08-31

Is it possible to replace the text content of my tag with via CSS?

FYI - I want this to be a pure CSS solution

For example I have:

<fieldset >         
  <legend>Current address</legend>
  <div >
    some content
  </div>
</fieldset>

I have accomplished something similar with replacing the text of an element at the end of a block, however that doesn't seem to be doing the same trick here...

I have tried the following: This adds text before the text we want to replace

.fieldset-class legend {
  visibility: none;
  content: none;
}

.fieldset-class legend:before {
  visibility: visible;
  content: 'hello';
}
<fieldset >         
  <legend>Current address</legend>
  <div >
    some content
  </div>
</fieldset>

This replaces the text, but instead adds the new text within the fieldset section with the content itself rather than on the container

.fieldset-class legend {
  display: none;
}

.fieldset-class:before {
  visibility: visible;
  content: 'hello';
}
<fieldset >     
  <legend>Current address</legend>
  <div >
    some content
  </div>
</fieldset>

Am I missing something here?

CodePudding user response:

You can use

  • text-indent and float

.fieldset-class legend {
 text-indent:-100vw;
}

.fieldset-class legend:before {
  float:left;
  text-indent:0;
  background:white;
  content: 'hello';
}
<fieldset >         
  <legend>Current address</legend>
  <div >
    some content
  </div>
</fieldset>

  • Or font-size

.fieldset-class legend {
font-size:0;
}

.fieldset-class legend:before {
  font-size:1rem;
  content: 'hello';
}
<fieldset >         
  <legend>Current address</legend>
  <div >
    some content
  </div>
</fieldset>

Note, the text will remain the original text for screenreaders and search engines, it might not be a good idea.

CodePudding user response:

As @Tushar said CSS is not the way to go about this. You could use both a before and after pseudo element one with the default text and one with the new text and then a media query to hide and show them or change the content. Or even hide and show different span or p elements. But there will still need to be some sort of logic as to what controls what shows. Example below using media queries.

.swap {
width: 600px;
height: 200px;
background-color: gray;
position: relative;
}

.swap::before {
content: 'show on large';
position: absolute;
left: 20px;
top: 20px;
}

@media screen and (max-width: 768px) { 
.swap::before {
content: 'show on tablet';
position: absolute;
left: 20px;
top: 20px;
}
}
<div >
</div>

  • Related