DEV Community

Discussion on: Daily Challenge #37 - Name Swap

Collapse
 
alvaromontoro profile image
Alvaro Montoro • Edited

There are a few answers in JavaScript already, so let's try some things in CSS 🤩

We could separate the words into <span> and, using Flexbox, change the order in which they are displayed within the parent container using the order property. It can be easily expanded to more than 2 words, but it requires that wrapping to work.

div {
  display: inline-flex;
}

div > span {
  margin-right: 1ch;
}

div span:nth-child(1) { order: 2; }
div span:nth-child(2) { order: 1; }

Without having to add any additional tags, we can use data-attributes to have the name and last name, and use the ::before and ::after to display them in inverted order. It is really simple to implement but not too extendable:

<div data-first="Name" data-last="Surname"></div>

div::before {
  content: attr(data-last) ' ';
}

div::after {
  content: attr(data-first);
}

Also without having any additional tags, we can play with multiple text-shadows and positioning to replicate the words in inverted order. For this solution, you need to know the size of each word, and it doesn't work for more than two words... still it is a cool approach too.

<div>Name Surname</div>

div {
  box-sizing: border-box;
  display: inline-block;
  font-family: monospace;
  font-size: 1rem;
  height: 1rem;
  overflow: hidden;
  padding-top: 1rem;
  text-shadow: -5ch -1rem, 8ch -1rem;
}

You can see a demo of all of them on CodePen:

Collapse
 
coreyja profile image
Corey Alexander

Oh damn! That box Shadow solution is pretty damn impressive!