"Step-by-Step Guide to Dividing and Centering Text Sections with Dynamic

Initially, my intention is to implement the concept outlined below. The webpage has dual potential states. In the first scenario, two texts (with potentially varying lengths) are centralized together as a header. When transitioning to the second state, the texts individually center on the page at distinct positions. This transition is triggered by pressing a button and executed smoothly.

https://i.sstatic.net/i9cIn.png

While my code is in Vue, I believe that I require assistance with CSS for this particular issue. Here is my current best effort:

export default {
  name: 'App',
  data() {
    return {
      solved: false,
    };
  },
  methods: {
    change_solved() {
      this.solved = !this.solved;
    },
  },
};
.cat_num {
  position: fixed;
  transition: all 2s ease;
  display: inline;
}

.cat_num.active {
  font-size: 40px;
  top: 100px;
}

.cat_name {
  position: fixed;
  transition: all 2s;
  display: inline;
}

.cat_name.active {
  font-size: 50px;
  top: 200px;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.17/vue.js"></script>
<template>
<button v-on:click="change_solved">Solve</button>
<h1 class="cat_num" :class="{active : solved}">Text 1</h1>
<h1 class="cat_name" :class="{active : solved}" >Text 2 (possibly lengthy)</h1>
</template>

Vue SFC Playground

The transition functions correctly. The issue lies in achieving consistent alignment of the texts.

I would greatly appreciate any guidance or feedback on this matter. Although it seems like a simple problem, I have already invested a significant amount of time into finding a solution. Thank you!

Answer №1

To achieve center alignment for both texts, a simple positioning technique using position: absolute can be employed and applied to the texts. By positioning the texts relative to the center anchor, they can be centered effectively as shown:

var app = new Vue({
  el: "#app",
  data: {
    solved: false,
  },
  methods: {
    change_solved() {
      this.solved = !this.solved;
    },
  },
})
.container {
  position: relative;
}

.cat_num {
  transition: all 2s ease;
  position: absolute;
  right: 50%;
  top: 0;
  transform: translate(0, 0);
}

.cat_num.active {
  font-size: 40px;
  top: 100px;
  transform: translate(50%, 0);
  text-align: center;
}

.cat_name {
  transition: all 2s;
  position: absolute;
  left: 50%;
  top: 0;
  transform: translate(0, 0);
}

.cat_name.active {
  font-size: 50px;
  top: 200px;
  transform: translate(-50%, 0);
  text-align: center;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.17/vue.js"></script>

<div id="app">
  <button v-on:click="change_solved">Solve</button>
  <div class="container">
    <h1 class="cat_num" :class="{active : solved}">Text 1</h1>
    <h1 class="cat_name" :class="{active : solved}">Text 2 (possibly lengthy)</h1>
  </div>
</div>

The issue with the lengthy text arises when it extends beyond a single line, impacting the smoothness of the transition due to changes in text alignment (using text-align: left or text-align: center). To address this problem, an edit was made as follows:

var app = new Vue({
  el: "#app",
  data: {
    solved: false,
  },
  methods: {
    change_solved() {
      this.solved = !this.solved;
    },
  },
})
.container {
  position: relative;
  text-align: center;
}

.cat_num {
  transition: all 2s ease;
  right: 50%;
  top: 0;
  transform: translate(0, 0);
  display: inline;
  position: static;
}

.cat_num.active {
  font-size: 40px;
  top: 100px;
  transform: translate(50%, 0);
  text-align: center;
  position: absolute;
}

.cat_name {
  transition: all 2s;
  left: 50%;
  top: 0;
  transform: translate(0, 0);
  display: inline;
  position: static;
}

.cat_name.active {
  font-size: 50px;
  top: 200px;
  transform: translate(-50%, 0);
  text-align: center;
  position: absolute;
  
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.17/vue.js</script>

<div id="app">
  <button v-on:click="change_solved">Solve</button>
  <div class="container">
    <h1 class="cat_num" :class="{active : solved}">Text 1</h1>
    <h1 class="cat_name" :class="{active : solved}">Text 2 (possibly lengthy)</h1>
  </div>
</div>

However, transitioning between states with this method may result in a sudden jump to the middle. This occurs due to changes in the position property. To resolve this issue, a JavaScript workaround involving the calculation of left and right values while maintaining position: absolute is recommended:

var app = new Vue({
  el: "#app",
  data: {
    solved: false,
    isMounted: false,
  },
  computed: {
    textsTotalWidth() {
      if (!this.isMounted) {
        return 0
      }
      
      return (this.$refs.catNum.offsetWidth + this.$refs.catName.offsetWidth) / 2
    },
    catNumRight() {
      if (!this.isMounted) {
        return ''
      }
      
      return `calc(50% + ${this.textsTotalWidth - this.$refs.catNum.offsetWidth}px)`
    },
    catNameLeft() {
      if (!this.isMounted) {
        return ''
      }
      
      return `calc(50% - ${this.textsTotalWidth - this.$refs.catNum.offsetWidth}px)`
    }
  },
  methods: {
    change_solved() {
      this.solved = !this.solved;
    },
  },
  mounted() {
    this.isMounted = true;
  }
})
.container {
  position: relative;
}

.cat_num {
  transition: all 2s ease;
  position: absolute;
  top: 0;
  transform: translate(0, 0);
}

.cat_name.active {
  font-size: 50px;
  top: 200px;
  transform: translate(-50%, 0);
  text-align: center;
  left: 50% !important;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.17/vue.js></script>

<div id="app">
  <button v-on:click="change_solved">Solve</button>
  <div class="container">
    <h1 ref="catNum" class="cat_num" :class="{active : solved}" :style="{'right':catNumRight}">Text 1</h1>
    <h1 ref="catName" class="cat_name" :class="{active : solved}" :style="{'left':catNameLeft}">Text 2 (possibly lengthy)</h1>
  </div>
</div>

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

Scrolling through image galleries with automatic thumbnails

I am looking to create an automatic image scrolling feature on my webpage using a bunch of images I have. I have searched for a solution but have not found one that fits my requirements. I don't think a carousel is the right approach for this. The sol ...

Tips for adding and removing active class with navbar links using JavaScriptonclick

I need help with toggling the "li-active" class on my navigation bar links. Currently, when I click on a link, the "li-active" class is transferred from the previous link to the newly clicked link instead of removing it first. Can someone please assist me ...

Is there a way to view the full HTML source code of this page by selecting the "more" button?

Exploring a web page related to forex trading can be an interesting experience. The website provides a list of live trade records, which can be accessed here: Typically, I use Python along with BeautifulSoup to extract information by reading the source co ...

I attempted to utilize the <map> tag in creating a circular image that functions as a hyperlink, but unfortunately, it is not functioning correctly

I've been trying to create a round button using the code below, but something seems to be wrong with it. The issue I'm facing is that the area around the image is also clickable, even though I have used border-radius. Can someone please take a lo ...

Utilizing Bootstrap, the layout structure consists of 4 columns for desktop, 3 columns for small laptops, 2 columns for tablets, and

I need assistance with setting up responsive columns in my HTML code using Bootstrap. Specifically, I want 4 columns per row on desktop, 3 columns per row on tablet, and 2 columns per row on mobile devices. Despite searching on Stack Overflow, I couldn&apo ...

Is Asp.net 4 resetting the array with every new run?

I have developed a basic asp.net web page to generate HTML content. The concept is to store previous user inputs in an array each time they click a button, and display them along with the most recent input. However, I encountered an issue where the array a ...

Error message in Angular js: Unable to load file using XMLHttpRequest

Encountering an error while debugging an Angular JS application in the WebStorm IDE. The error message states: "XMLHttpRequest cannot load file:///C:/Users/../list.html. Cross origin requests are only supported for HTTP." Provided Javascript code : var a ...

Specific solution in responsive design queries

Looking to modify the style of a div based on screen resolution. Here is an example: @media only (width: 320px){do something} I attempted using this code but it was not successful. Appreciate any assistance! ...

Symfony 2 lacks the ability to automatically create the web/bundle/framework structure

I encountered a major issue with Symfony. After installing Symfony 2.7.5 via the command line: $ symfony new my_project The problem arose in the generated project directory: /web/bundle In this folder, I found two empty files (not directories!) named fr ...

Children transform when the parent element is being hovered

I need assistance with changing the child element when the parent is hovered over. I also want to modify an attribute of the parent at the same time. Specifically, I want the background color of #action to change and also adjust the color of the a or h1 el ...

I am working with two dropdown menus and I need to search the database for data that matches both selections. Unfortunately, the code I have written does not seem to be functioning correctly

I am facing an issue with a dropdown filter in my PHP code. I have 3 pages and the dropdown is working for one filter, but I am unable to make it work for both filters simultaneously. I suspect it's a syntax error since I am new to PHP. I have tried v ...

What is the best way to access the index in a v-for loop in Vue.js?

Here is an example of my Vue component: <div v-for="item in items" :key="I need to access the index of the for-loop here" > </div> ... data(){ items: [{name:'a'}, {name:'b'}...] } Is there a way to retrieve the inde ...

Guide for Vue.js Bootstrap Table: Retrieving and Storing Row IDs in a Data Property

I'm working with a Vue.js Bootstrap table and I need to store each table row id in either an Array or Object data property. Below is a sample bootstrap table template: <template v-slot:cell(label)="row" > <div > ...

What is the reason behind the inconsistent behavior of Javascript's Date.getDate() and .setDate() methods?

As a hobbyist coder, I'm facing a challenging problem with building a dynamic HTML/CSS calendar. My goal is to have cells filled in based on today's date. However, when I attempt to add days to fill in another 13 days by looping through HTML elem ...

The fullCalendar plugin fails to display properly when placed within a tab created using Bootstrap

My current challenge involves integrating fullCalendar into a Bootstrap tab. It works perfectly when placed in the active tab (usually the first tab), however, when I move it to another tab that is not active, the calendar renders incorrectly upon page loa ...

The center alignment doesn't seem to function properly on mobile or tablet devices

I've designed a basic webpage layout, but I'm facing an issue with responsiveness on mobile and tablet devices. The problem seems to be related to the width: 100% property in my CSS, but I can't seem to pinpoint the exact solution. While tr ...

The functionality to deselect multiple options in a select box is not functioning properly

There seems to be an issue with removing the selected attribute from the selected values in a jQuery multiselect box. The console is not showing any errors. You can view a working example here The problem lies in this code snippet: $("#mltyslct option ...

SVGs appear at the forefront of all other elements

is where this issue is arising.... specifically in the date selection feature on the left side of the options panel. When using both Google Charts and Material Icons with the date picker component from https://github.com/nickeljew/react-month-picker, we a ...

What are the best ways to format an outgoing email using inline CSS?

On my upcoming website, I have set up a single form for guests to subscribe. The issue I am facing is with styling the email that is sent upon submission. I attempted using inline CSS, but it doesn't seem to be working. Instead of transforming the cod ...

HTML tends to disregard the dimensions specified in the JavaScript file

I'm currently working on replicating an Etch-a-Sketch style drawing board where hovering over a single pixel with the mouse changes its color. However, I've hit a roadblock when it comes to drawing the board. The flexbox container doesn't se ...