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

Only the cursor CSS is applied to the parent div, not its individual elements within the div

The current issue with the CSS is that it doesn't apply to the cursor setting. It only works if I set cursor:not allowed; to the .bar class and not specific elements like .bar p. My objective is to have all the p elements initially set to not-allowe ...

Challenges related to maintaining a webpage's content using AJAX

I have a form that I want to use to send and insert the values into my database. After the values are inserted, I would like to clear the input fields of the form and display a success message. Here's an example of how I would like it to look: Clear ...

Placing two texts alongside a logo in a Bootstrap Navbar: Step-by-step guide

As I venture into the world of Bootstrap, I am on a quest to create a Navbar Component similar to this design: https://i.stack.imgur.com/NidKQ.png I attempted to use the Navbar Image and Text code, but encountered an issue where the text would only displ ...

Setting expiration dates for cached images

I am interested in optimizing the loading speed of my webpage by setting an expiration date for images. However, I am unsure about where to specify this. The images on my website are loaded via CSS from Cloudfront using an S3 bucket in AWS. Can you provid ...

The system considers the resource as a script, yet it was transmitted with the MIME type of text

I am encountering an issue when trying to integrate AngularJS/JavaScript into my HTML document. Each time I try to load my index.html file, the following error message appears: Resource interpreted as Script but transferred with MIME type text/html: "http ...

html5-jquery checkbox change event not firing

I successfully implemented an on/off switch using the method outlined in for HTML5. The functionality of the switch itself is working perfectly - click on it to toggle between states and query the checked state of the input/checkbox. However, I am facing ...

How to use Jquery to fetch the value of a td element nested inside another

After consulting the manual, I am trying to find a way to extract the value in the second column of a table when a specific span is clicked. However, the challenge is that the click event is currently being triggered by the first span cell. Here is the jQu ...

vue popup input will automatically receive focus

Currently, I am utilizing Vue 2.x Within a HTML file that is included in a JSP file, the structure looks like this: <html> <body> <div id="myDiv"> <input type="text" v-model="input" @click=&qu ...

What are the advantages of implementing HTML5 canvas for animation?

I'm a beginner in html5 and I've recently been experimenting with the canvas element. Can anyone provide insight on when the canvas would be most beneficial or practical to use? Essentially, what are some scenarios where it is recommended to util ...

What are the differences in how a link tag responds on mobile devices?

I have a question regarding opening a pdf in an iframe on the current page. Is there a way to handle this differently for mobile/tablet users? For example, clicking the link could open it in another tab for better readability instead of within the iframe ...

Design a custom Bootstrap dropdown using an input[type="text"] element

After exploring the Bootstrap dropdown example here, I realized that for my particular scenario, it would be more beneficial to have an input field (type="text") instead of a button. This way, I can display the selected option from the dropdown. Is there ...

A single button that performs multiple actions with just one click

Summary: Seeking assistance in implementing a button that triggers three different actions upon being clicked thrice. Detailed description: On one page of my website, there is an introduction with text and images. I currently have a button that switches t ...

Updating Vue component with mismatched props

I am looking to optimize the Vue component where data is received in varying structures. Take for example Appointment.vue component: <template> <div> <div v-if="config.data.user.user_id"> {{ config.data.user.user_id ...

A step-by-step guide on making a list item clickable and redirecting to a URL using Vue.js

Utilizing vue.js, I have successfully configured a navigation bar with multiple list elements. However, I am seeking guidance on how to redirect one of the list elements to an external website, such as https://www.google.com/. Within my router file, each e ...

Attempting to follow along with a guide to create a Spring Boot Vue.js project, encountering a few errors along the way

I am currently following a tutorial on building a Spring Boot project with Vue.js from this GitHub page. I have successfully created an empty Vue project using the command vue create frontend --no-git and proceeded until the step where it says: "Calling a ...

Tips for structuring a SQL query result in an AngularJS application

Forgive me if this code is not up to par with the best standards, as I am still relatively new to angular.js. The issue I am facing is that when the data is returned from my query, it appears as a block of text. Despite using echo statements in search.php ...

Adjust the color of a label based on a set threshold in Chart.js

Can anyone help me with my Chart.js issue? Here is a link to the chart: I am trying to change the color of the horizontal label when it falls between 70.00 - 73.99. Does anyone know if there's a specific option for this in Chart.js? Thanks! ...

What is the solution for resolving the error "Uncaught TypeError: Cannot read property '_wrapper' of undefined" while utilizing webpack in conjunction with Vue?

When I am utilizing axios to fetch data from the database, I receive a server response in an array format: In my HTML tags: The JavaScript code appears as follows: data() { return { departments: { id: 0, ...

Master the Art of Image Loading in Codeigniter

Hey there, I'm completely new to Codeigniter. In the Controllers folder, I've created a file called caller.php and in the \Views directory, I've created a file named home1.php. Additionally, within the root directory, I've made an ...

Angular encountering issues with loading external JavaScript files due to the error: ENOENT - indicating that the specified file or directory does

I am attempting to incorporate a bootstrap template into Angular. The template requires some external JavaScript and CSS files that need to be linked. I have placed these files in the assets folder and referenced them in the styles and scripts arrays of an ...