Trouble with the width of the message container in CSS styling

I need to display a message at the top-center of my webpage. I have created a simple example for this:

http://jsbin.com/eniwax/3/edit

The issue I am facing is with the width of the message container. I want the container width to adjust dynamically based on the width of the message text (i.e., auto width that changes according to the message size).

Answer №1

Follow this method VIEW DEMO

Here's how it's done: Create a nested div structure where the container div has a width of 100% and apply text-align: center; to the container div.

Custom CSS

.test {
    top: 0;
    text-align: center;
    position: relative;
    width:auto;
    z-index: 100;
    border: 1px solid #F0C36D;
    background-color: #F9EDBE;
    font-size: 12px;
    font-weight: bolder;
    padding : 4px;
    display: inline-block;
}

.container {
  width: 100%;
  text-align: center;
}

HTML Structure

<!DOCTYPE html>
<html>
<head>
<meta charset=utf-8 />
<title>Example</title>
</head>
<body>
  <div class="container">
  <div class="test">This is a sample text</div>
  </div>
</body>
</html>

Answer №2

Instead of using a standalone <div />, consider using a <span /> within your div.

Divs are known as block level elements, meaning they take up the full width available to them. On the other hand, spans are inline elements, adjusting their width based on their content.

Answer №3

Apply display: inline-block; and text-align: center; to the parent element.

body {text-align: center;}
.test
{
    top: 0;
    text-align: center;
    position: relative;
    width:auto;
    display: inline-block;
    z-index: 100;
    border: 1px solid #F0C36D;
    background-color: #F9EDBE;
    font-size: 12px;
    font-weight: bolder;
    padding : 4px;

}

See a live demo here: http://jsbin.com/eniwax/15

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

What prompts JQuery to interpret ajax responses as xml in Firefox?

let url = "/MyApp/pspace/filter"; let data = JSON.stringify(myData); $.post( url, data, function(response, textStatus, jqXHR) { console.log("response: " + response); }, "json" ); In actuality, the expected type of response is a JSON string. ...

Discovering the right place to establish global data in Nuxt JS

Exploring the world of NuxtJS today, I found myself pondering the optimal method for setting and retrieving global data. For instance, how should a frequently used phone number be handled throughout a website? Would utilizing AsyncData be the most effecti ...

Tips for Optimizing Typescript Queries to SQL Server

In my C# application, I have the following function: foreach (var p in proglist) { programData.GetData1= new List<GetData1_ViewModel>(GetData1(programid, reportingdate)); programData.GetData2= new List<GetData2_ViewModel>(GetData2(programid ...

Using the useRef hook to target a particular input element for focus among a group of multiple inputs

I'm currently working with React and facing an issue where the child components lose focus on input fields every time they are re-rendered within the parent component. I update some state when the input is changed, but the focus is lost in the process ...

Unable to show inline within web forms application utilizing bootstrap

I am currently modifying the account registration section of a new VS 2013 web application that uses bootstrap css for formatting. I am working on creating a form on a page and struggling to get one section to display inline instead of as a block element. ...

Getting the Mongoose Model using Express parameters is a simple process

Is it possible to dynamically fetch a mongoose model based on the req.params.model? Check out this example of a Schema const mongoose = require("mongoose"); const Schema = mongoose.Schema; const SmartSchema = new Schema({ SmartPriority: { type: Stri ...

Parent controller was not in command before Child执行

When working with a parent view and a child view, I encounter an issue with accessing a json file. In the parent view, I retrieve the json file using the following code: $scope.services = Services.query(); factory('Services', function($reso ...

The class instances are not invoking the decorators

I'm experiencing issues with my decorators. It seems that the decorators are not being invoked on every instance of the class. While I understand that decorators are called during declaration time, I am wondering if there is a way to call them for eac ...

Tips for resolving an issue with an array and the find method?

Seeking guidance on using the find method. Specifically, I am tasked with searching an array to find a specific string match. The catch is that this string may be nested within one of the objects in its child array. I attempted to create an if statement in ...

retrieving data from a php file using ajax for a post request

Utilizing ajax, I have invoked the page search.php: function search(){ var title=$("#search").val(); if(title!=""){ $.ajax({ type:"post", url:"sear ...

Shifting Directive Logic to a Method within a Vue Component

I am currently working with a VueJS component that utilizes the style attribute in the following way: <section :style="{ backgroundImage: src && 'url(' + src + ')' }"> ... <script> export default { props: [& ...

Manipulating state in React

Currently, I am enrolled in Samer Buna's Lynda course titled "Full-Stack JavaScript Development: MongoDB, Node and React." While working on the "Naming Contests" application, I encountered a piece of code within the App component that has left me puzz ...

Combine Vue Plugin Styles without Using Components

Question Time To clarify, when I mention 'without component', I am referring to my plugin being a custom Vue Directive that does not rely on a template. It acts as a wrapper for a class, without the need for an additional component. However, I a ...

Transform an object into an array using JavaScript with the help of Lodash, Azure Functions, and Azure Logic Apps

To achieve the desired result of extracting JSON from a proprietary content management system, transforming it into a CSV, and depositing that CSV in an Office 365 shared drive, a combination of Azure Function and Azure Logic App is utilized. The Node/Java ...

Developing a Navigation Bar Menu using JSON data and the power of Lodash

Seeking advice to enhance my code for creating a navbar menu from JSON data. Any suggestions on how to avoid calling getItems multiple times? Appreciate any feedback, thank you! var _ = require('lodash'); let menuConfig = [ { ID: 1 ...

Incorporating PHP variables within JavaScript

As a beginner in web development, I am working on creating an application that heavily relies on JavaScript but also includes PHP/MySQL to prevent users from viewing quiz answers by inspecting the page source. The key pages involved in this project are: in ...

Navigating React Router: Updating the page on back button press

Looking for a solution to a persistent issue. Despite various attempts and exhaustive research, the problem remains unresolved. Here's the situation: Within my React-Router-Dom setup, there is a parent component featuring a logo that remains fixed an ...

Creating a React component in Typescript to utilize lodash helper functions

I have a component that looks like this: import React, { Component } from 'react'; import throttle from 'lodash.throttle'; interface Props { withScroll: boolean; } class Image extends Component<Props, {}> { throttledWindowS ...

Arrange the text in a div element in a horizontal direction

While developing a friends list script for a website, I encountered an interesting UI issue in the chat section. When a lengthy chat message is added to the chat content div with the CSS attribute overflow: scroll, it causes the div to stretch out horizont ...

Automatically formatting text upon entering it in Vue.js

I need assistance with auto-formatting the postal code entered by the user. The rule for the postal code is to use the format A0A 0A0 or 12345. If the user inputs a code like L9V0C7, it should automatically reformat to L9V 0C7. However, if the postal code ...