Center align button

How TO — Center a Button in DIV

Learn how to center a button element vertically and horizontally with CSS.

How To Center a Button Vertically

Example

.vertical-center margin: 0;
position: absolute;
top: 50%;
-ms-transform: translateY(-50%);
transform: translateY(-50%);
>

How To Center Vertically AND Horizontally

Example

.center margin: 0;
position: absolute;
top: 50%;
left: 50%;
-ms-transform: translate(-50%, -50%);
transform: translate(-50%, -50%);
>

Читайте также:  Python получить размер файла

You can also use flexbox to center things:

Example

.center <
display: flex;
justify-content: center;
align-items: center;
height: 200px;
border: 3px solid green;
>

Tip: Go to our CSS Align Tutorial to learn more about aligning elements.

Tip: Go to our CSS Transform Tutorial to learn more about how to scale elements.

Tip: Go to our CSS Flexbox Tutorial to learn more flexbox.

Unlock Full Access 50% off

COLOR PICKER

colorpicker

Join our Bootcamp!

Report Error

If you want to report an error, or if you want to make a suggestion, do not hesitate to send us an e-mail:

Thank You For Helping Us!

Your message has been sent to W3Schools.

Top Tutorials
Top References
Top Examples
Get Certified

W3Schools is optimized for learning and training. Examples might be simplified to improve reading and learning. Tutorials, references, and examples are constantly reviewed to avoid errors, but we cannot warrant full correctness of all content. While using W3Schools, you agree to have read and accepted our terms of use, cookie and privacy policy.

Источник

Как выровнять кнопку по центру используя CSS и HTML

Чтобы расположить кнопку в центре HTML страницы, можно использовать 3 разных подхода:

Как использовать margin: auto для центрирования кнопки

Первый и, возможно, самый простой вариант — добавить кнопке CSS свойство margin: 0 auto , а затем добавить display: block , чтобы сделать кнопку в центре.

button < margin: 0 auto; display: block; > 

margin: 0 auto — это краткая форма установки верхнего и нижнего полей в 0 и левого и правого полей на авто.

Автоматическое поле — это то, что заставляет кнопку центрироваться. Тут важно, чтобы кнопка находилась внутри блока.

Как центрировать кнопку с помощью HTML тега div

Второй вариант — обернуть кнопку тегом div , а затем использовать text-align: center для центрирования кнопки внутри этого .

Как будто ты размещаешь текст по центру.

div> button>Centered buttonbutton> div> 

Обратной стороной этого подхода является то, что каждый раз, когда ты хочешь центрировать кнопку, тебе придется создавать новый элемент div только для этой кнопки.

А если у тебя много кнопок, которые требуют частого обновления стиля, поддерживать их быстро становится проблемой.

В таком случае лучше использовать первый вариант.

Короче говоря, если вы настаиваете на использовании этого подхода, сделайте это только для редких кнопок.

Как центрировать кнопку с помощью CSS flexbox

Третий вариант — использовать flexbox для центрирования кнопки.

Этот подход идеален, если ты уже используешь flexbox на веб-странице, а кнопка находится внутри родительского элемента.

Чтобы центрировать кнопку с помощью flexbox , ты должен сделать 2 вещи:

  • сначала добавь display: flex к родительскому элементу кнопки, чтобы активировать функции flexbox
  • затем добавь justify-content: center , чтобы кнопка была по центру

В приведенном ниже примере div является родительским элементом кнопки.

div < display: flex; justify-content: center; > 
div> button>Centered buttonbutton> div> 

Теперь ты знаешь 3 способа центрирования кнопки в CSS!

Источник

Center Align CSS Button

Styling and formatting are what all web developers and designers want to apply to their web pages and application to look attractive. It is up to the creator how they want to use Cascading Style Sheets and Hypertext Transfer Protocol to provide the best style for their web page and application.

Users specifically use CSS to add the best attractive look to their web pages and specify the arrangements of the page elements in a systematic order. This article will discuss how to center a button in the HTML page using CSS.

You can Center Align CSS Button using the following method:

  1. text-align: center — By setting th text-align property of the parent div tag to the center
  2. margin: auto — By setting margin property to auto
  3. Center Button Vertically AND Horizontally
    1. By setting th text-align property of the parent div tag to the center
    2. By setting position property to 50% from top and bottom
    3. By setting margin property to auto

    1. By placing a text-align property of body tag to the center (text-align: center)

    In this example, we are using `text-align` center property on the tag, so everything inside the tag will be center-aligned automatically.

        body   

    1.1 By setting text-align property of parent div tag to the center (text-align: center)

    In this example below, we are using `text-align` center property on tag with a class ( button-container-div ) so everything inside this will be center-aligned automatically.

          .button-container-div  

    2. Center CSS Button by using margin auto (margin: auto)

    In this example, we are using the `margin` auto property. Margin auto moves the div to the center of the screen.

        .button-container-div  

    3. Center Button Vertically AND Horizontally

    3.1: By setting the text-align property of the parent div tag to the center

    We use the text-align property with the parent div tag to align the button to the center. Let us grab a look at this CSS code snippet and understand how to align the button to the center of the HTML page using CSS

    In this example, we are using text-align: center property to the parent div and button position 50% from top «top: 50%;«.

         .button-container-div < text-align: center; >.button  

    In this example, we have used HTML and CSS to align the button on the web page to the center. Here, we discuss the code block in detail:

    We have assigned the style information of the button using the HTML tag. The text-align property of CSS aligns the inline-level content (here button) to a horizontal alignment. In this example, we used text-align: center property to the parent div and button position 50% from top «top: 50%;».

    Then, we used the HTML tag that acts as a container of the CSS text-align property. Lastly, we added a button on the web page using the HTML tag. The web page will look like this:

    3.2: By setting position property to 50% from top and bottom

    We assigned only one property to the button element in the earlier example. This example will show two positions for the top and bottom. We use position property to tag with left: 50% & top: 50%

       .button  

    Explanation:

    The above example shows how to align the button in the HTML page using two position properties of the CSS element. Here, we set the position property as «fixed» and align the button to the center using two properties, namely left and top — to 50%. Finally, we used the HTML button> tag inside the tag to create the main page button.

    3.3: By setting margin property to auto

    In this example, we are using margin: auto CSS property to tag

       .button    

    Explanation:

    In this example, we are using margin: auto CSS property to tag. This property will set the alignment of the CSS button with white spaces. The margin property creates spaces around elements, and we are assigning it to «auto.» Inside the button element of the tag, we add some styles using properties like height, width, top, bottom, left, right, and position that define the button alignment. Finally, we add the HTML tag inside the tag to create the main page button.

    4. Center CSS Button using Position fixed

    In this example, we are giving a 50% margin from the left side of the page, and then we are taking the position: fixed so it will adjust the position on the center of the body.

          button  

    5. By setting the display property to flex (display: flex)

    In this example we are using `display` flex property, `justify-content` and `align-items` to the parent tag with class (button-container-div). The button inside will take place in the center of vertical and horizontal position.

    • Display flex will move it to the center vertically.
    • Justify-content will move the button to the center horizontally.
    • Align-items center keeps it in the center; otherwise, it will start from the div and go at the bottom of the div.
          .button-container-div  

    6. By setting the display property to the grid (display: grid)

    In this example, we are using `display` grid property on the tag with class ( button-container-div ). The button inside will take place in the center of vertical and horizontal positions.

        .button-container-div < width: 100%; height: 300px; border: 1px solid #ff8899; display: grid; >button  

    7. Using CSS Bootstrap

    In CSS Bootstrap we can use class «text-center» as given in the example

         

    Explanation:

    We will see how to use the CSS Bootstrap with the class «text-center» in this last example. Inside the button, we used the tag with type and class attributes. The rel attribute of the tag defines the relation between the current and the linked document.

    The integrity attribute allows the browser to check the fetched script, and the crossorigin attribute sets the request mode to an HTTP CORS Request.

    We hope this article has given a crisp idea of how to align the button in the HTML page using different approaches to CSS. We have shown alignment vertically and horizontally using text-align, margin, and position properties of the tag in HTML and CSS Bootstrap.

    • Difference between Sensor and Transducer
    • BitTorrent vs Utorrent
    • Difference between GSM and CDMA
    • Difference between NSE and BSE
    • HTML Button Link
    • HMO vs. PPO
    • Diploma vs. Degree
    • Difference between FOR and WHILE Loop
    • Woocommerce vs Shopify
    • Difference between Structure and Union in C
    • Difference between StringBuffer and String
    • Difference between Money Market and Savings
    • Difference between Marketing and Selling
    • Arduino vs Raspberry Pi
    • Difference between Data and Information
    • Differences between Malloc and Calloc Functions in C Language
    • Visa vs Mastercard
    • Mutex vs Semaphore
    • Difference between Analog and Digital Signal
    • Difference between Microprocessor and Microcontroller

    Источник

    How to center a button element using HTML and CSS

    Last Updated Aug 15, 2022

    To center an HTML element, you need to add certain CSS properties that will put the button at the center of your HTML web page.

    Button center horizontally with text-align

    The text-align property is used to specify the horizontal alignment of text in a block element.

    One trick of this property is that it can also be used to set the alignment of children elements in a parent tag.

    For example, suppose you have a tag that contains two buttons. You need to add text-align to the tag as follows:

    
    

    Using text-align to center button elements

    Button center horizontally using margin auto

    Alternatively, you can also set the button in the middle of the tag.

    Set the display property to block and add margin: 0 auto to the tag as shown below:

    Using margin auto to center a button

    This is useful when your button has no parent element.

    How to center button horizontally and vertically

    To center a horizontally and vertically, you can use a combination of display , justify-content , and align-items properties.

    Suppose you have a as the container of the element.

    Use css class to make your code tidy as follows:

     Next, create another CSS class rule with the align-items property and set it to center .

    Also add the display property here so that you can center vertically without the center-h class.

    To see the content centered vertically, let’s add one more class to set the element height to 500 :
    Finally, add all the classes assigned to the CSS rule above to the containing tag as follows:
    The output will be as shown below:

    Using CSS to center a button horizontally and vertically

    To center the button vertically but not horizontally, remove the center-h class:

    Now you’ve learned how to center a

    And that’s how you can center an HTML button element using CSS properties!

    CSS is very useful for styling your web page elements, but it’s quite tricky to learn what rule to write and what property to use.

    The guides I’ve written will help you to understand how to style HTML elements with CSS.

    Learn JavaScript for Beginners 🔥

    Get the JS Basics Handbook, understand how JavaScript works and be a confident software developer.

    A practical and fun way to learn JavaScript and build an application using Node.js.

    About

    Hello! This website is dedicated to help you learn tech and data science skills with its step-by-step, beginner-friendly tutorials.
    Learn statistics, JavaScript and other programming languages using clear examples written for people.

    Type the keyword below and hit enter

    Tags

    Click to see all tutorials tagged with:

    Источник

Оцените статью