Search code examples
cssreactjstext-alignment

center placeholder of type span


I have created a span which acts as a placeholder for figcaption. I am trying to center the placeholder but it is creating some padding(not sure) which I cannot control. Here is the link for code sandbox. sanbox

I have tried commenting out property width:0 which indeed centered the caption but the focus is misbehaving now.

This is the react component for span which acts as placeholder

<span
 contentEditable={false}
 style={{
    pointerEvents: "none",
    display: "inline-block",
    width: "0",
    maxWidth: "100%",
    whiteSpace: "nowrap",
    opacity: "0.333"
 }}
>
 Figure Caption
</span>

To reproduce the bug, please open the sandbox, place your cursor inside editor, and click on insert image button. As soon as you click it an image with caption gets inserted. Placeholder inside it is not centered.


Solution

  • Just remove width: "0" from settings. In a centered parent and child, the width:0 for a block (or inline-block) child element, puts it in the center of parent (in fact it puts the left of element in the center of parent) and if it contains text or any type of content, the content will grow to the right (The content overflows the zero-width element).

    To overcome the focus problem there are some workarounds:

    First Idea: using margin-left. You may still use width:0 but you have to set margin-left equal to half width of caption text. This idea needs more coding to calculate the dynamic width of caption as soon as text changes (onKeyup event).

    Another Idea: Remove the width:0 but: Hide the default caption as soon as user clicks on the cpation and set it back again if the user input was null. You may hold the default caption in a data-caption tag to recover it easily.