Center user input within a div element

I am trying to achieve proper alignment of input elements within a div. When the div is clicked, the input should be displayed; otherwise, a span should be shown instead.

Here is my code:

<!doctype html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>Document</title>
    <style>
      .cell-wrapper {
        display: inline-flex;
        align-items: center;
        width: 100px;
        border: 1px solid #ccc;
        padding: 0;
        margin: 0;
      }
      .cell-wrapper,
      .cell-wrapper input {
        height: 50px;
        font-size: 15px;
      }

      .cell-wrapper span {
        padding: 0 6px;
      }

      .cell-wrapper input {
        width: 100%;
        box-sizing: border-box;
      }
    </style>
  </head>
  <body>
    <div id="root">
        <div>
            <table-cell v-for="col in cols" :key="col"/>
        </div>
    </div>
    <script src="https://unpkg.com/vue@3/dist/vue.global.js"></script>
    <script>
      const TableCell = {
        template: /*html*/ `
        <div @click="editing = true" class="cell-wrapper">
            <input
                v-if="editing"
                v-model="val"
                class="col"
                @blur="editing = false"
                @vue:mounted="({ el }) => el.focus()"
            />
            <span v-else>{{ val }}</span>
        </div>
        `,
        setup() {
          const editing = Vue.ref(false)
          const val = Vue.ref('')
          return {
            val,
            editing
          }
        }
      };
      const app = Vue.createApp({
        setup() {
          const cols = Vue.ref(5)
          return {
            cols,
          }
        }
      })
      app.component('table-cell', TableCell)
      app.mount('#root')
    </script>
  </body>
</html>

This code produces the following output:

https://i.stack.imgur.com/wVUVD.png

However, when I change the input value, the rendered page does not align the table-cells horizontally as expected:

https://i.stack.imgur.com/Ybk1U.png

I suspect that the issue lies with the CSS, but I am unable to identify the exact reason behind it.

Answer №1

To align the elements vertically, you can use the following CSS code on the parent div: display: flex

#root > div {
    display: flex;
    align-items: center;
}

<!doctype html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>Document</title>
    <style>
      .cell-wrapper {
        display: inline-flex;
        align-items: center;
        width: 100px;
        border: 1px solid #ccc;
        padding: 0;
        margin: 0;
      }
      .cell-wrapper,
      .cell-wrapper input {
        height: 50px;
        font-size: 15px;
      }

      .cell-wrapper span {
        padding: 0 6px;
      }
      
      #root > div {
        display: flex;
        align-items: center;
      }

      .cell-wrapper input {
        width: 100%;
        box-sizing: border-box;
      }
    </style>
  </head>
  <body>
    <div id="root">
        <div>
            <table-cell v-for="col in cols" :key="col"/>
        </div>
    </div>
    <script src="https://unpkg.com/vue@3/dist/vue.global.js"></script>
    <script>
      const TableCell = {
        template: /*html*/ `
        <div @click="editing = true" class="cell-wrapper">
            <input
                v-if="editing"
                v-model="val"
                class="col"
                @blur="editing = false"
                @vue:mounted="({ el }) => el.focus()"
            />
            <span v-else>{{ val }}</span>
        </div>
        `,
        setup() {
          const editing = Vue.ref(false)
          const val = Vue.ref('')
          return {
            val,
            editing
          }
        }
      };
      const app = Vue.createApp({
        setup() {
          const cols = Vue.ref(5)
          return {
            cols,
          }
        }
      })
      app.component('table-cell', TableCell)
      app.mount('#root')
    </script>
  </body>
</html>

Answer №2

Here is some CSS code that may help with your issue:

.box-container {
      align-items: center;
      width: 100px;
      border: 1px solid #ccc;
      padding: 0;
      margin: 0;
    }

    .box-container,
    .box-container input {
      height: 50px;
      font-size: 15px;
      display: flex;
      text-align: center;
    }

    .box-wrapper {
      display: flex;
      flex-direction: row;
    }

    .box-container span {
      padding: 0 6px;
      width: 100%;
    }

    .box-container input {
      width: 100%;
      box-sizing: border-box;
    }

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Attempting to include html5shiv.js in my project to ensure compatibility with Internet Explorer for proper rendering

<!DOCTYPE html> <html lang="en"> <head> <meta charset="utf-8"/> <meta name="Description" content="C.V"/> The code snippet below was added to try and render in Internet Explorer, unfortunately it did not work as expected. < ...

What is the best way to retrieve all information from GitLab API using Axios?

I am looking to retrieve data from all the projects stored on my GitLab server. As I understand, GitLab usually displays a default of 20 projects per page, so I need to adjust the setting to show more projects at once: https://gitlab-repo.com/api/v4/proje ...

Retain the formatting of HTML while extracting the text

Is there a simple way to extract text from HTML source without losing formatting (such as line breaks and spaces)? Currently, my text extraction process looks like this: page_title_element = driver.find_element_by_xpath("x-path") page_title = pa ...

Using Bootstrap: adjusting the height of input-group and select elements

How come the select element within an input-group doesn't render similarly to the input element? I would like the height of the select element to be relative to the input-group. <link href="https://maxcdn.bootstrapcdn.com/font-awesome/4.7.0/css ...

What is the best way to switch between my two images upon clicking?

When I click on an image, it changes to a different image. I achieved this by altering the source of the image upon clicking. Now, my goal is to incorporate a smooth transition between the two images after they are clicked. I attempted to stack the two im ...

Creating dynamic DIV elements in an AngularJS file using data retrieved from a Sql server

I need to dynamically add elements based on data retrieved from a MSSQL server in the specified area: <div id="ApplicationForm" class="tabcontent" style="display:none;"> <div class="tab_section"> ...

What is the best way to trigger a function after the v-model has been updated

When attempting to filter an array of objects in Vue using input, I encountered issues with Salvattore not functioning correctly for building a grid of the filtered elements. It seems that calling the rescanMediaQueries() function after changes to my v-mod ...

Make Bootstrap Panel Full Width with Highcharts Data

I am currently working on displaying graphs using the Highcharts library on three televisions. All televisions have a FULL HD resolution of 1920 x 1080. I have one Bootstrap panel containing a graph in the panel-body. <div class="panel panel-blue"> ...

Having Trouble with JQuery Triggering Tabs inside an iFrame

I am curious why this code functions properly on my parent's HTML page: $("#assessmentsTab").trigger("click"); but fails to work within my iFrame: $("#assessmentsTab", window.parent.document).trigger("click"); Does anyone have any suggestions? I ...

Transform HTML into PDF while maintaining the original letter spacing

We are in need of converting numerous files to enable search and word highlighting functionality in a web browser, as well as server-side indexing for the searchable words. I have previously utilized an online service like (Step 1, Step 2 on linked page) ...

Designing the chosen choice with CSS and HTML: Making it look like a placeholder and keeping it hidden in the dropdown menu

UPDATE: I'm puzzled by the 2 downvotes without any solutions to my problem. Issue: The challenge I'm facing is styling the color of the selected option that acts as a placeholder. I attempted different solutions like this one, but unfortunate ...

Turning off v-navigation-drawer for certain routes in Vue.js

I currently have a v-navigation-drawer implemented in my webpage using the code below in the App.vue file. However, I am looking to disable it on certain routes, such as the landing page: <v-app> <v-navigation-drawer id ="nav" persistent : ...

What causes the undefined value of "this" in the Vue Composition API setup function?

A Vue component I've created is using v3's composition API: <template> <input type="checkbox" v-model="playing" id="playing" @input="$emit('play', $event.target.value)" /> <labe ...

Tips on maintaining expanded rows in a table within Element UI

My table from element-ui is draggable: <table-card> <el-table-draggable @drop="changeDossiertypesOrder" handle=".handler"> <el-table :data="dossiertypes" v-loading="dossie ...

Creating dynamic color changes with overlapping SVG triangles using CSS

I'm facing a challenging issue: I want to change the color of an SVG line as it intersects with a triangular background created using CSS. Although I've experimented with gradients, they don't produce the desired effect. My goal is for the ...

Reposition a Single Item on the Top Menu to the Right

I'm new to HTML and CSS and I need help aligning the "Login" item to the right. I'm trying to create a horizontal menu bar, but not sure if I'm approaching it correctly. Something similar to this: How I want it to be Here is the code I have ...

Updating a property on an object during iteration

Currently, I am in the process of developing a Single Page Application using Laravel on the backend and Vue.js. I have two arrays that are crucial to my project: The first array is accessArray: ["BIU","CEO","Finance","HRD","Group"] The second array is a ...

What is the method for selecting the element currently under the mouse cursor?

Is it possible to change the color of all elements you hover over using plain Javascript without jQuery? HTML <ul> <li></li> <li></li> <li></li> </ul> JavaScript (function() { var item = ...

Resize the images and align them side by side

I have a container with a maximum width of 1400px. Inside this container, there are two images of different sizes. I want to align them in a row using flexbox so that they fit within the 1400px width and still maintain a visually appealing appearance as sh ...

When a selection element has a CSS box-shadow animation applied to it, it reverts to its default settings when expanded or clicked

A user notified me of an issue with a select element that has an animated box-shadow on it. I confirmed the problem on my work Windows computer, but unfortunately, I don't have access to a Windows setup at home for debugging. The select element in qu ...