簡體   English   中英

為什么我不能使用 text-align: center 在 html 中將這個文本類型的表單輸入字段居中?

[英]Why can't I center this form input field of type text in html using text-align: center?

我正在學習 HTML 並且我正在嘗試實現一個搜索欄,但它需要居中。 我已經在谷歌上搜索了大約 4 個小時,但我無法做到。 我已經嘗試了很多教程,但它們都不起作用。

在按鈕中,CSS 規則text-align: center; 有效,但在搜索欄中無效。 我正在使用 Bootstrap 來幫助設置 web 頁面的樣式。 無論如何,這是我的 HTML 代碼:

 #search-bar { height: 50px; width: 50%; border: 2px solid black; border-radius: 25px; }
 <form action="https://google.com/search"> <div class="form-row"> <div class="form-group col-lg-12" style="text-align: center;"> <input type="text" name="q" class="form-control" id="search-bar"> </div> </div> <div class="form-row"> <div class="form-group col-lg-12" style="text-align: center;"> <input type="submit" class="btn btn-primary" value="Google Search"> </div> </div> </form>

我采取的方法不同。 使用 CSS,您可以添加margin-left: 25%以便將元素主體的 25% 向右移動。 這樣,如果您將元素寬度設置為 50%,它將最終居中。 在這種情況下,這是我的 css:

#search-bar {
    margin-top: 100px;
    width: 50%;
    margin-left: 25%;
    border: 2px solid black;
    border-radius: 25px;
}

嘗試這個:

#search-bar { 
              display : flex;
              justify-content : center;
              align-items : center;
            }

有關 flex-box 樣式的更多詳細信息: https://css-tricks.com/snippets/css/a-guide-to-flexbox/

文本對齊:居中; 如果您使用引導程序,由於寬度限制而無法工作,那么您可以嘗試使用“ml-auto”和“mr-auto”

<div class="form-group col-lg-12 mr-auto ml-auto">
  <input type="text" name="q" class="form-control" id="search-bar">
</div>

或者如果你想使用普通的 css 那么你可以指定屬性

邊距:0 自動;

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM