Dynamically Align Text and Divs within Fieldsets

Struggling with vertically centering text in a fieldset, especially when a sibling element is hidden.

View the correct code example to see how it should look when the sibling element is visible:

    #title {
      margin: 20px;
    }
    
    #definition {
      margin: 0 auto;
      margin-top: 5%;
      text-align: center;
      max-width: 60%;
      font-size: 1.5vmax;
    }
    
    hr {
      color: white;
      background-color: white;
      width: 80%;
      height: 1px;
    }
    
    #formulaLine {
      color: white;
      background-color: white;
      height: 1px;
    }
    
    section#formula {
      width: auto;
      max-width: 70%;
      background: #393e46;
      box-shadow: inset 2px 5px 10px rgb(24, 23, 23);
      border-radius: 5px;
      margin: 5% auto;
      padding: 10px;
      font-size: 2vmax 1vmin;
    }

     <!-- Additional CSS code -->

    
    <div>
      <fieldset class="tBox">
        <legend class="legend">Definition</legend>
        <div id="definition">Answers if we did what we said we would do. BECAUSE IT'S LONG I'LL ADD EXTRA TEXT TO SHOW MULTI-LINE EFFECT</div>
        <div>
          <hr>
          <section id="formula">
            <div class="row">
              <p class="column center" style="margin-top: 5%; margin-left: 3%;">Formula:</p>
              <div class="column center">
                <p>∑ # completed tasks in month 'A' (from month 'B' schedule)</p>
                <hr id="formulaLine">
                <p>∑ # tasks forecased to finish in month 'A'</p>
              </div>
            </div>
          </section>
        </div>
      </fieldset>
    </div>

However, when the formula sibling (in React) is hidden, the definition text does not center as expected. It ends up looking like this:

The CSS for this case is the same as above. What could be causing this issue? despite trying various options such as Top, Float, the problem persists without a solution.

Answer №1

If you want to enhance your markup to accommodate the use of :only-child in CSS, I suggest looking into this useful pseudo-class that targets an element without any siblings. Make sure to check out the documentation for more examples.

/* Selects each <p>, but only if it is the only child of its parent. */
p:only-child {
  background-color: lime;
}

This feature can be handy in scenarios like this, and incorporating it won't require many modifications.

var formula = document.createElement("P");
formula.innerText = "This element represents your formula being added to the container which removes the styles applied with :only-child.";
var active = false;
function toggleFormula() {
active = !active;
document.getElementById("legend").innerText = active ? "Click here to hide formula." :
 "Click here to show formula.";

let tbox = document.getElementById("t-box");
if (active)
tbox.appendChild(formula);
else
tbox.removeChild(formula);
}
.container { position: relative; }
.legend {
  position: absolute;
  top: -10px;
  left: 20px;
  z-index: 1;
  padding: 0.2em 0.8em;
  background: #d65a31;
  border-radius: 25px;
  width: auto;
  min-width: 200px;
  font-size: 3vmax 2vmin;
  font-family: 'Lato', sans-serif;
  cursor: pointer;
}
#definition {
  margin: 0 auto;
  margin-top: 5%;
  text-align: center;
  max-width: 60%;
  font-size: 1.5vmax;
}
#definition:only-child {
  position: absolute;
  top: 50%;
  left: 50%;
  transform: translate(-50%, -50%);
}
.tBox {
  position: relative;
  width: auto;
  max-width: 100%;
  min-height: 400px;
  max-height: 500px;
  background-color: #222831;
  border-radius: 5px;
  margin: 40px auto;
  align-content: center;
  color: #eeeeee;
  box-shadow: 0 2px 4px 0 rgba(0, 0, 0, 0.16), 0 2px 10px 0 rgba(0, 0, 0, 0.12) !important;
  font-family: 'Lato', sans-serif;
}
#definition {
  margin: 0 auto;
  margin-top: 5%;
  text-align: center;
  max-width: 60%;
  font-size: 1.5vmax;
}
#definition:only-child {
  position: absolute;
  top: 50%;
  left: 50%;
  transform: translate(-50%, -50%);
}
<div class="container">
<legend id="legend" class="legend" onclick="toggleFormula();">Click here to show formula.</legend>
<fieldset id="t-box" class="tBox">
<div id="definition">Answers if we did what we said we would do. BECAUSE IT'S LONG I'LL ADD EXTRA TEXT TO SHOW MULTI-LINE EFFECT</div>
</fieldset>
</div>

You also have the option of utilizing position: absolute or display: flex:

/* Absolute Version */
#definition.centered {
    position: absolute;
    top: 50%;
    left: 50%;
    transform: translate(-50%, -50%);
}

/* Flex Version */
.tBox {
    display: flex;
    align-items: center;
    justify-content: center;
    flex-direction: column;
}

Answer №2

To enhance your current code, simply include a few properties in your CSS for an easy solution. Utilizing Flex properties can greatly assist in these situations - align-items: center will vertically align all elements within the div, while justify-content: center will horizontally align the items.

section#formula {
    width: auto;
    max-width: 70%;
    background: #393e46;
    box-shadow: inset 2px 5px 10px rgb(24, 23, 23);
    border-radius: 5px;
    margin: 5% auto;
    padding: 10px;
    font-size: 2vmax 1vmin;
    display: flex;
    justify-content: center;
    align-items: center;
}

.center {
    justify-content: center;
    display: flex;
    width: 100%;
    flex-flow: row wrap;
}

For a visual representation, you can view it here.

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

Issue with Anchor class in CakePHP where the variable $action is not defined

I'm struggling to apply a class to my anchor link when it is active. How should I define the $action variable in this case? Version: 4.2.9 Error: Undefined variable: action [ROOT\templates\layout\default.php, line 108] templates/lay ...

What is the best way to display the current time (generated through JavaScript) within a designated div element?

During my JavaScript studies, I stumbled upon the following code snippet: function printTime() { var d = new Date(); var hours = d.getHours(); var mins = d.getMinutes(); var secs = d.getSeconds(); document.body.innerHTML = hours+":"+mins+":"+sec ...

The HTML.LabelFor function is failing to display correctly

I am facing an issue with Html.LabelFor where it doesn't render properly. Instead of displaying the value of ProviderName like "AT&T," it just shows the text ProviderName instead of the actual value. <div id="ServiceProvider" class="main_filter" n ...

Identify the moment an iframe becomes visible

I am currently facing an issue where my website is embedded within another website. However, I need to find a way to detect when my iframe is being shown in order to execute a specific script. Here is an example of what I am trying to achieve: <div id ...

Launch the modal and automatically navigate to a designated DIV

I am trying to open a modal window with a link and scroll to a specific DIV inside it. HTML: <a href="#teamMembers" data-toggle="modal" class="teamMemebrScroll1">read more</a> <a href="#teamMembers" data-toggle="modal" class="teamMemebrS ...

Having Difficulty Positioning Tooltip Beside Input/Label Field

I have created a tooltip using HTML and CSS that appears when hovering over an image. However, I am encountering alignment issues when placing the image next to a textbox/input as it is not inline with the input box, likely due to some absolute positioning ...

"What is the significance of the .default property in scss modules when used with typescript

When dealing with scss modules in a TypeScript environment, my modules are saved within a property named default. Button-styles.scss .button { background-color: black; } index.tsx import * as React from 'react'; import * as styles from ' ...

Utilizing Bootstrap 4 for a responsive layout: positioning a <div> element adjacent to a centered image

I am currently working on a project involving an image gallery. My goal is to showcase the images in a specific layout: https://i.sstatic.net/cXcql.png Essentially, the image should always be centered. If there is sufficient space to the right, I want to ...

Tips for styling carousel images seamlessly (HTML/CSS/Bootstrap4)

I am a beginner in HTML, CSS, and Bootstrap and I am currently working on implementing a carousel on my webpage. Although the carousel is functional, I am facing an issue with the images not fitting properly on the page. The size of the images appears to ...

Keeping information saved locally until an internet connection is established

I have a vision to develop a Web app focused on receiving feedback, but the challenge lies in the fact that it will be utilized on a device without an internet connection. The plan is for it to save any user input offline until connectivity is restored. Th ...

Preventing click events with pointer-events property in CSS while still allowing scrolling

Is there a way to use pointer-events: none to disable click events on a specific container while still allowing scroll functionality and an overlay? You can view my fiddle here: https://jsfiddle.net/1eu6d3sq/1/ Currently, when I apply pointer-events: non ...

"Want to know the trick to make a Vuetify component stretch to fill the rest of the screen's

Imagine a scenario where there is content above and below a table on a webpage. The goal is to get the table to occupy the remaining height of the page without affecting other elements. This ensures that the content below the table is always visible at the ...

Mistake in Timestamp Separation - JavaScript

I have a Timestamp retrieved from MSSQL and displayed on a Webclient. The timestamp reads: Thu Jan 01 18:00:00 CET 1970, however, I am only interested in the time format: 18:00 or 18:00:00 (preferably the former). <script> var timestamp = ...

`vertical navigation on the left side with expanding submenus`

Trying to create a navigation system on the left side of the page with submenus appearing on the right without impacting the main content. If anyone has any code snippets or resources that can help achieve this, I would really appreciate it. The objectiv ...

Tips for adjusting the up and down controls and spins of a date input after modifying its height

After adjusting the height of my inputs (date type) to 40px, I noticed that the up and down controls are no longer aligned with the text inside the field. I am looking for a solution to either adjust the height of the spins or remove them if necessary in ...

From horizontal to vertical: Transforming Bootstrap navigation orientation

How can I transform a horizontal navigation row with dropdown menu items into a vertically stacked accordion-style nav when the screen size decreases? I prefer the accordion stacking functionality over converting it to a burger menu. However, I'm str ...

What strategies can be used to accurately position a rotated image within a rotated div?

Below is the code snippet I am using: <div class="container"> <img class="img"/> <div class="underlay"></div> </div> The image is a picture of some rotated text by 10 degrees, although the ...

Tips for iterating through a JSON object in JavaScript and building a table from it

My JSON data is structured like this: diferencias = { "1": { "1": 543.0, "0": 542.0 }, "2": { "0 1": 0.3333333333333333 } } I am trying to create a table with the outer keys as columns. This is the code I have written ...

AngularJS - Custom directive to extract a property value from an object

Currently, I am using the following for loop to retrieve the parent category: angular.forEach(queryTicketCategories, function(category) { if(category.id === $scope.ticketCategory.parentId) { $scope.parent = category; } }); I am looking fo ...

The Bootstrap flex-grow-0 class did not work as intended in my navigation bar

My webpage has a navbar that currently looks like this Click here for an image example of the code output This is the code I have written for the navbar: <nav class="navbar navbar-expand-sm fixed-top bg-white"> <div class="container my-2" ...