Search code examples
csstextalignmentparent

Center a text with his parent


I'm not very good at CSS, I guess that will we easy to one of you.

Look at image below, i'm trying to center my text but center it with the div parent's width, as if there was no button, but I don't know how to proceed.

<div class="parent" style="width:500px;">
    <div class="container" style="width:400px;"> My text here </div>
    <button style="width:100px;">My Button</button>
</div>

I tried :

.parent { text-align: center; }

but that center the text with the .container width (so at 200px) but i'm looking for a way to center it a 250px here (.parent width)

I think about doing that with a padding-left but that's not a "clean" method in my case because button is not always displayed.

If someone knows how can I do that please :)

image:

enter image description here


Solution

  • One option would be to use absolute positioning on the button!

    .parent {
      position: relative; // position the button within the parent div
    }
    
    button {
      position: absolute;
      right: 0;
      top: 0; // or whatever, position it where you want it
    }
    
    
    .container {
      padding-right: 100px; // so the text doesn't overlap with the button
      padding-left: 100px; // so the text is balanced 
    
      text-align: center;
    }

    EDIT:

    And when the button isn't needed, you could use a conditional on the parent --

    .container--with-button {
      padding-right: 100px;
      padding-left: 100px;
    }
    .container--without-button {
      padding: 0;
    }