Fluid centering of DIV content both vertically and horizontally

Check out this example:

When dealing with fluid divs, line height won't work as expected. My current code relies on line-height which doesn't work when the box sizes change. How can I ensure that a link (content) always appears perfectly centered?

I need to guarantee that the content within this DIV is consistently centered both vertically and horizontally.

Current code: (please note that the style tag is empty as it gets populated dynamically)

 <style type="text/css">
    .box{
    width:468px; /* sometimes changed by PHP */
    height:60px; /* sometimes changed by PHP */
    background:#eee;
    text-align:center;
    border:1px solid rgb(177, 172, 171);
    line-height: 61px;
    }
    </style>

    <div style="" class="box" id="">
        <a style="color:#333;font-weight:bold" href="claimPrize();">Winner!</a>
    </div>

Answer №1

Recently encountered a similar scenario and stumbled upon an article on absolute centering from css-tricks, you can check it out here. There's also a fiddle included for testing purposes.

CSS

/* The container with flexible dimensions */
.block {
  text-align: center;
}

/* The invisible element to assist in perfect centering */
.block:before {
  content: '';
  display: inline-block;
  height: 100%;
  vertical-align: middle;
  margin-right: -0.25em; /* Adjustment for spacing */
}

/* Element to be centered, also flexible in size */
.centered {
  display: inline-block;
  vertical-align: middle;
  width: 300px;
}

HTML

<div class="block" style="height: 300px;">

    <div class="centered">
        <h1>Some text</h1>
        <p>But he stole up to us again, and suddenly clapping his hand on my shoulder, said&mdash;"Did ye see anything looking like men going towards that ship a while ago?"</p>
    </div>

</div>

<div class="block" style="height: 200px;">

    <div class="centered">
        <h1>Some text</h1>
        <p>But he stole up to us again, and suddenly clapping his hand on my shoulder, said&mdash;"Did ye see anything looking like men going towards that ship a while ago?"</p>
    </div>

</div>

<div class="block" style="height: 600px;">

    <div class="centered">
        <h1>Some text</h1>
        <p>But he stole up to us again, and suddenly clapping his hand on my shoulder, said&mdash;"Did ye see anything looking like men going towards that ship a while ago?"</p>
    </div>

</div>

Demo

http://jsfiddle.net/andresilich/YqKMH/

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

Ways to modify the jquery script to display on page load rather than on scrolling action

Currently in the process of working on my site, www.runebs.dk. Utilizing a script to activate information for each project. JS.. $('.showHide').on('click',function(){ $(this).toggleClass('active'); $( '#subHead ...

The absence of a closing parentheses in the argument is causing an issue when rendering

Apologies for the basic mistake, but I could really use some assistance with this syntax error. I've spent over an hour searching for it and still haven't been able to locate the issue. It seems to be around the success function(data) section. Th ...

Problem with CSS multi-level dropdown navigation in a vertical layout

I am in the process of creating a navigation menu with dropdown menus, which are working correctly. Now, I would like to add another sub-menu drop down inside dropdown 1, but I am having trouble getting it to function properly. How can I make Sub Menu 1 ac ...

Out-of-sync movement in animated characters

Looking for some assistance with my page coding. I have a scenario where two stars are moving around a button, simulating an animation by incrementing the CSS properties top and left. Initially, everything appears fine and they move synchronously. However, ...

Styling CSS: Create circular images with dynamic text positioning or resizing on screens larger than 768px

I'm struggling to figure out how to create a circular profile picture on a background image that remains responsive and maintains its position across different screen sizes. Currently, I've been using fixed margin values to adjust the position, ...

How to align radio_button_tag and label_tag side by side in Rails using Twitter Bootstrap 2?

Struggling to align the radio_button_tag horizontally with its label_tag. (Utilizing HAML) =radio_button_tag(:animal, "dog") =label_tag(:animal, "Dog") Which classes should I use for these form helpers to have them positioned side by side as shown below: ...

rendering google charts using jade template

I am facing an issue while trying to display a google annotated chart on my jade project. I managed to successfully load a pie chart, but I am having trouble rendering a chart that requires the container element size to be explicitly defined. You can find ...

The structure becomes disrupted when the Material Ui grid is enclosed within a div container

I currently have a responsive dashboard built with Material Ui's Grid elements. One of the grid items is wrapped in a div element, causing the layout to break. Check out the playground with the div element here: https://codesandbox.io/s/basicgrid-mat ...

The mysterious case of the vanishing jQuery traversal box

I'm currently navigating using previous and next buttons, but it seems to be malfunctioning if I click too quickly. My goal is for the navigation to remain smooth without breaking. var $currDiv = $("#start"); $("div").hide(); $currDiv.c ...

Set a maximum height for an image without changing its width dimension

I am facing an issue with an image displayed in a table. The image is a graph of profiling information that can be quite tall (one vertical pixel represents data from one source, while one horizontal pixel equals one unit of time). I would like to set a ma ...

Execute HTML and JS files through Eclipse PDT to view in a web browser

Is it possible to open HTML and JS files in a web browser within Eclipse PDT? Right now, only PHP files seem to launch successfully, otherwise an "Unable to Launch" dialog pops up. Any advice is appreciated! ...

How to perfectly position various height <a> elements in a WordPress mega menu

I'm currently working on a WordPress mega menu with four columns, each with a heading or top menu item. The headings should have a gradient border at the bottom and differ in length. However, I'm facing an issue where some headings span two lines ...

Break up a line within an ionic element by inserting a linebreak tag

Currently, I am constructing an app using ionic framework and facing a challenge in inserting a linebreak within an ionic tag to ensure proper display inside the designated container... <h2>{{caravan.model}}</h2> ...

Developing a Multi-Stage Pop-Up with Jquery

I am interested in creating a custom multi-step modal This particular div has dynamically generated classes $('.modal-content').append('<div class="modal-body step step-' + key + '" data-step="'+key+'"></div> ...

What is the process for inserting a new column into an order list on Opencart?

I'm looking to customize the table in opencart's admin dashboard by adding a new column for 'company name' between 'Customer' and 'Status'. Can anyone guide me on how to achieve this? Which specific file do I need t ...

inputting an array of strings into the value attribute of an input element using jQuery

Whenever a user writes something in the input field with id="clientAdd" and presses enter, that text should be displayed as a tag inside a div. These tags are then saved as an array of strings, which I want to pass as the value for the hidden input field w ...

The horizontal overflow is malfunctioning, resulting in only a limited number of columns being visible on the screen

I am facing an issue with the CSS for my table. Despite using overflow-x: scroll, only half of the columns are being displayed on the screen out of the 15 total columns. Can anyone provide assistance with this problem? .table { font-family: Roboto,"He ...

ERB failing to interpret Ruby script

Hello, my index.html.erb file looks like this: <h1>Bookmarks</h1> t <% @books.each do |b| %> <div class="book"> e <div class="row"> s <div class="col-md-1"> t <p class="rank-this ...

Utilize xdebug and NetBeans 8.2 to troubleshoot PHP code submitted through an HTML form

After successfully setting up the XDebug extension to debug PHP code within NetBeans IDE (ver. 8.2), I encountered an issue. While debugging works fine when setting a breakpoint and running the script in debug mode, I am having trouble debugging PHP code t ...

Displaying VueJS property inside an array of HTML elements

Currently, I am working with an HTML array that contains the following data: data-groups='["category_all", "data goes here"]' In my project, there is a prop named "title" that holds the specific string needed to be displayed in the "data goes he ...