Center two elements within a div container both horizontally and vertically

I am trying to vertically center a text and a button within a container. The text should be positioned in the middle of the div, while the button should be aligned to the right.

What is the best way to achieve this layout where the text element is centered and the button is on the right side?

My current code looks like this:

* {
  margin: 0;
}

body {
  color: #ffffff;
  background-color: #4a4a4a;
}

#header {
  height: 60px;
  background-color: #313132;
}

#headerTitle {
  font-weight: bold;
  text-align: center;
  font-size: 30px;
  top: 50%;
  left: 50%;
}

#menuBtn {
  right: 20%;
}
  <div id="header">
    <p id="headerTitle">Title</p>
    <button id="menuBtn">Menu</button>
  </div>

Answer №1

To center the text in the header of a button with average size, you can utilize the flex model and apply some left padding. This will ensure that the text is positioned neatly in the middle.

For example, you can include a gradient effect to visually display the center alignment.

* {
  margin: 0;
}

body {
  color: #ffffff;
  background: #4a4a4a;
}

#header {
  height: 60px;
  background: linear-gradient(to right, transparent 50%, rgba(0,0,0,0.25) 50%),
             linear-gradient(to top, transparent 50%, rgba(0,0,0,0.25) 50%) #313132;
  display: flex;
  align-items: center;
  padding-left: 2.75em; /* adjust this value based on the width and potential right margin of the button for proper alignment */
}

#headerTitle {
  font-weight: bold;
  text-align: center;
  font-size: 30px;
  margin: auto; /* centers the element */
}

#menuBtn {
  margin-right: 0; /* pulls the button to the right */
}
<div id="header">
    <p id="headerTitle">Title</p>
    <button id="menuBtn">Menu</button>
  </div>

Answer №2

Start by centering h1 by setting the line-height to match the height of the header, and using text-align:center

Next, for centering the menu:

#menuBtn {
  position:absolute;
  right:20px;
  top:50%;
  transform:translateY(-50%);
}

Here, top:50% moves the menu down by 50% of the header's height, and then transform:translateY(-50%); moves the menu up by 50% of its own height, effectively centering it vertically within the header

Refer to the code snippet below:

* {
  margin: 0;
}

body {
  color: #ffffff;
  background-color: #4a4a4a;
}

#header {
  height: 60px;
  background-color: #313132;
position:relative;

}

#headerTitle {
  font-weight: bold;
  text-align:center;
  font-size: 30px;
line-height:60px;


}

#menuBtn {
  position:absolute;
right:20px;
top:50%;
transform:translateY(-50%);
}
<div id="header">
    <p id="headerTitle">Title</p>
    <button id="menuBtn">Menu</button>
  </div>

Answer №3

To easily incorporate a button into your text, simply place it within the <p> tags.

<p id="headerTitle">Title<button id="menuBtn">Menu</button></p>

If you'd like to create some space between the text and the adjacent button, you can achieve this by adding margin properties to the button:

#menuBtn {
  right: 20%;
  margin-left: 20px;
}

Answer №4

  1. Place them within the same container inside another container
  2. Avoid specifying the width and height of the inner container
  3. Ensure that the inner container has text-align = "center"
  4. Adjust the padding of the outer container to your liking

    This is how your layout will appear:

outerWrap{
innerWrap{

  <p> , <h1>   

           }   
      }

Answer №5

It is always recommended to do some research and try to resolve the issue on your own before seeking help. There are numerous resources available online that can assist with this type of question, so a quick Google search should provide some guidance.

For those looking for information on vertical alignment, check out this resource.

In response to your query and based on the details you have shared, the following code snippet may be helpful:

* {
  margin: 0;
}

body {
  color: #ffffff;
  background-color: #4a4a4a;
}

#header {
  height: 60px;
  background-color: #313132;
}

#headerTitle {
  font-weight: bold;
  text-align: center;
  font-size: 30px;
}

#menuBtn {
  display: block;
  margin: 0 auto;
}


/* --- */

.float {
  height: 75px;
  width: 50%;
  display: block;
  float: left;
  background: #f0f;
}

.align {
  position: relative;
  top: 50%;
  -webkit-transform: translateY(-50%);
  -ms-transform: translateY(-50%);
  transform: translateY(-50%);
}
<div id="header">
  <div class="float">
    <p id="headerTitle" class="align">Title</p>
  </div>
  <div class="float">
    <button id="menuBtn" class="align">Menu</button>
  </div>
</div>

Best regards,

-B

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

The application of document.body.style.backgroundColor is not compatible with an external CSS style sheet

Why does document.body.style.backgroundColor not work with an external CSS style sheet? I have the following CSS: body { background-color: red; } In my css style sheet, when I use JavaScript alert alert(document.body.style.backgroundColor);, it sh ...

Effortlessly retrieving the id attribute from an HTML tag using jQuery

Currently, I am encountering an issue with a code snippet that is designed to extract the value from an HTML tag. While it successfully retrieves a single word like 'desk', it fails when attempting to do so for an ID consisting of two or more wor ...

CSS: Aligning content vertically centered

Take a look at the following example: <div class="container"> <div class="box1"></div> <div class="box2"></div> </div> The height of box1 is smaller than that of box2. Is there a way to vertically center box1 w ...

bridging information from tables with text fields in forms

I am working on an HTML/CSS page that utilizes a table layout filled with buttons to mimic a T9 keypad design. Within the page, I have a form containing two text fields. My aim is to populate these text fields with numbers based on the values from the tab ...

How to enable drag-and-drop functionality for an iframe?

I've successfully made a chat widget draggable using react-draggable. However, the chat widget is also consumed by an iframe created entirely with HTML. I need the iframe to be draggable as well, but react-draggable doesn't support this. Are ther ...

How can we display the Recent Updates from our LinkedIn profile on our website using iframe or javascript?

Currently, I am in the process of developing a .NET web application for our company's website. We already maintain an active LinkedIn profile where we regularly post updates. https://i.stack.imgur.com/T2ziX.png My main query at this point is whether ...

Tips for positioning the title of a card in Bootstrap-Vue

I'm currently working with the <b-card> component from bootstrap-vue and encountering an issue where I am unable to center align the title property. Does anyone have a solution for this problem? Below you can find the structure of my card, which ...

What are some effective ways to stretch specific muscles?

I am facing an issue with my select element. The default value is "please choose," but there are options like "Accommodation & Hotels" that are longer and not clearly visible on IE browsers, though they work fine in Firefox. How can I resolve this issue? S ...

Angular: seamlessly transferring all directives from parent component to child without interference

Imagine we have a component called main that includes another one named sub. I would like for the directive passed to main in the client side, such as: <main dir1='dirval1'></main> for the main component to act as a thin wrapper and ...

Issue with jQuery centering in IE browsers with jquery-ui-1.10.3.custom.js and jquery-ui-1.9.2.custom.js not working as expected

Are there any other alternatives you can recommend? Here is the dialog structure: <div id="dialogbox" title="message box"> <p>example content</P> </div> ...

Retrieving input values from different input types within a div using jquery

I have a dilemma with two divs that I switch between based on whether the user wants to add single select options or multiple. Only one div is visible at a time. <div class="form-group row" id="divOptions"> @Html.Label("Choices", htmlAttrib ...

Issue with PrimeFaces radiobutton styles not updating after being clicked programmatically

My setup includes a p:selectOneRadio constructed like this: <p:selectOneRadio id="positionRadio" value="#{employeeBean.empPosition}" converter="#{empPositionConverter}" layout="custom" required="true" requiredMessage="Please select ...

Tips for keeping a consistently viewable and editable iteration of your HTML form

How can I efficiently maintain both viewable and editable versions of the same HTML form? I am working on an application that has numerous custom data-entry screens with a high number of fields, and managing separate layouts for viewable and editable form ...

The issue with the stretched-link in Bootstrap 5 is that it is not functioning properly when used with a

I'm having a small issue with the stretched-link feature not working properly with my card. Despite trying everything from the Bootstrap documentation, including removing buttons as they are said to not work well with stretched-links, I still can&apos ...

Retrieve the index value within a given range

How do I retrieve the index number using PHP? foreach ($array as $index => $value) { // Use $index to access the index number } Is there a way to obtain the index number in Go language? {{ range .posts }} {{ index . }} {{ .Id }} {{ .Name}} ...

HTML5 canvas game issue: background fails to load

I'm a beginner at designing games using HTML5 canvas. I've been following a tutorial on creating games in the style of Angry Birds from the 'pro html5 games' book. I've completed all the steps in the tutorial, but I'm facing a ...

Guide to ensuring the navbar remains at the top of the webpage following an image

I am attempting to create a sticky navbar that stays at the top of the page once the header has been scrolled past. It should have a similar effect as shown in this example on codepen.io, but with the addition of an image that stretches across most of the ...

Sharing a document that contains a linked image file using a relative path through the `publish` feature

I have reviewed the documentation and tested the steps provided in this example, but I am still unable to find a solution for the issue at hand. Based on the documentation, the image file should either be located in the same path as the MATLAB script bein ...

Tips for customizing the cursor to avoid it reverting to the conventional scroll cursor when using the middle click

When you wish to navigate by scrolling with the middle mouse button instead of using the scroll wheel, simply middle-click and your cursor will change allowing for easy scrolling on web pages. Even though I am utilizing style="cursor: pointer" and @click. ...

Slicknav is failing to appear on the screen, although it is being

After spending hours trying to implement a slicknav menu into my school project, I'm stuck and seeking guidance. Despite having some coding experience, I can't seem to find the solution to my problem. Any help, insight, or tips on fixing or impro ...