write a text on the side of a centered text

I want to add a text beside a centered text without moving the centered text.

Example: C is a centered text and s is a side text:

+++++
 sC

+++++
ssC

+++++
sCCC

Is this possible with CSS?

3 answers

  • answered 2018-01-16 15:18 trichetriche

    Sure, use flexbloxes like this. This is gross, but at least it works.

    .container {
      display: flex;
      justify-content: center;
      align-items: stretch;
    }
    
    .container > * {
      border: 1px solid #ccc;
      padding: 6px 12px;
      box-sizing: border-box;
    }
    
    .side {
      flex: 1 1 50%;
      display: flex;
      flex-direction: row;
      flex-wrap: wrap;
    }
    
    .side:nth-child(1) {
      justify-content: flex-end;
    }
    
    .content {
      width: 200px;
      text-align: center;
    }
    <div class="container">
      <div class="side"><p>Side text</p><p>Side text</p></div>
      <p class="content">Content text</p>
      <div class="side"></div>
    </div>

  • answered 2018-01-16 15:23 Tibs

    Is this possible with CSS? Yes it is. If you're just exploring and playing around with CSS, you can do it by using :before or :after pseudo element. Set the positioning of the parent element to relative then set the pseudo element's position to absolute so you can control its positing inside the centered element div.

    However it is a bad practice if you will use this in your work.

    div.centered-element{
      text-align: center;
      width: 100%;
      background-color: #f0f0f0;
      position: relative;
    }
    
    div.centered-element:before{
      content: "sss";
      color: red;
      position: absolute;
      left: 30%;
    }
    <div class="centered-element">C</div>

  • answered 2018-01-16 15:27 Davey Contreras

    It sounds like if you are trying to display text before or after the element in which case you may want to read over https://developer.mozilla.org/en-US/docs/Web/CSS/::before

    See the example below.

    .container {
      width: 100%;
      background: #eee;
    }
    .center-text {
      display: table;
      margin: auto;
    }
    .center-text:before {
      content: "s";
      font-size: smaller;
    }
    
    .center-text:after {
      content: "s";
      font-size: smaller;
    }
    <div class="container">
      <div class="center-text">CCC</div>
    </div>