Philipp Jardas
Philipp Jardas

Reputation: 3302

Flex: how to apply styles to text child

Given the following HTML snippet...

<div class="container">
  Hello, World!
</div>

... I want to achieve a layout like this...

+----------------------------------------------------+
| x | Hello, World!                              | y |
+----------------------------------------------------+

... using flexbox layout and without changing the HTML structure.

My SCSS looks something like this:

.container {
    display: flex;
    flex-direction: row;
    justify-content: space-between;

    &:before {
        content: 'x';
    }

    &:after {
        content: 'x';
    }
}

which nearly does the right thing, except that the text content is horizontally centered instead of flush left.

Normally I would simply apply flex-grow: 1 to the content that I wish to have at full width, but in this case there simply is no content node.

So, how can I make the text content grow? Thanks!

Upvotes: 0

Views: 621

Answers (2)

Asons
Asons

Reputation: 87191

In a case like this, where the text is not wrapped in its own element, Flexbox create an anonymous wrapper, which one can't target using CSS.

One solution is to drop the justify-content and use auto margins instead, on the ::after pseudo element, shown below, another is to position the first pseudo ::before absolute.

Note, as flex-direction: row; is the default, you can omit it.

Stack snippet

.container {
  display: flex;
}

.container:before {
  content: 'x';
}

.container:after {
  content: 'x';
  margin-left: auto;
}
<div class="container">
  Hello, World!
</div>

Upvotes: 3

Nenad Vracar
Nenad Vracar

Reputation: 122027

You can use margin-left: auto on :after instead.

.container {
  display: flex;
  align-items: center;
  border: 1px solid black;
}

.container:after {
  content: 'y';
  margin-left: auto;
  padding: 5px;
}

.container:before {
  content: 'x';
  padding: 5px;
}
<div class="container">
  Hello, World!
</div>

Upvotes: 2

Related Questions